1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
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"
19 #include "glob-util.h"
22 #include "nulstr-util.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "stat-util.h"
26 #include "string-util.h"
28 #include "time-util.h"
31 int path_split_and_make_absolute(const char *p
, char ***ret
) {
38 l
= strv_split(p
, ":");
42 r
= path_strv_make_absolute_cwd(l
);
52 char *path_make_absolute(const char *p
, const char *prefix
) {
55 /* Makes every item in the list an absolute path by prepending
56 * the prefix, if specified and necessary */
58 if (path_is_absolute(p
) || isempty(prefix
))
61 return path_join(prefix
, p
);
64 int safe_getcwd(char **ret
) {
67 cwd
= get_current_dir_name();
69 return negative_errno();
71 /* Let's make sure the directory is really absolute, to protect us from the logic behind
82 int path_make_absolute_cwd(const char *p
, char **ret
) {
89 /* Similar to path_make_absolute(), but prefixes with the
90 * current working directory. */
92 if (path_is_absolute(p
))
95 _cleanup_free_
char *cwd
= NULL
;
97 r
= safe_getcwd(&cwd
);
101 c
= path_join(cwd
, p
);
110 int path_make_relative(const char *from_dir
, const char *to_path
, char **_r
) {
112 unsigned n_parents
= 0;
118 /* Strips the common part, and adds ".." elements as necessary. */
120 if (!path_is_absolute(from_dir
) || !path_is_absolute(to_path
))
123 f
= strdupa(from_dir
);
124 t
= strdupa(to_path
);
126 path_simplify(f
, true);
127 path_simplify(t
, true);
129 /* Skip the common part. */
138 /* from_dir equals to_path. */
141 /* from_dir is a parent directory of to_path. */
156 if (a
!= b
|| memcmp(f
, t
, a
) != 0)
163 /* If we're here, then "from_dir" has one or more elements that need to
164 * be replaced with "..". */
166 /* Count the number of necessary ".." elements. */
172 /* If this includes ".." we can't do a simple series of "..", refuse */
173 if (w
== 2 && f
[0] == '.' && f
[1] == '.')
176 /* Count number of elements */
183 r
= new(char, n_parents
* 3 + strlen(t
) + 1);
187 for (p
= r
; n_parents
> 0; n_parents
--)
188 p
= mempcpy(p
, "../", 3);
193 /* Remove trailing slash */
200 char* path_startswith_strv(const char *p
, char **set
) {
203 STRV_FOREACH(s
, set
) {
204 t
= path_startswith(p
, *s
);
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
= path_join(root
, orig
);
266 r
= chase_symlinks(t
, root
, 0, &u
, NULL
);
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)
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 stripped everything, we either need a "/" (for the root directory)
375 * or "." for the current directory */
387 int path_simplify_and_warn(
391 const char *filename
,
393 const char *lvalue
) {
395 bool fatal
= flag
& PATH_CHECK_FATAL
;
397 assert(!FLAGS_SET(flag
, PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
));
399 if (!utf8_is_valid(path
))
400 return log_syntax_invalid_utf8(unit
, LOG_ERR
, filename
, line
, path
);
402 if (flag
& (PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
)) {
405 absolute
= path_is_absolute(path
);
407 if (!absolute
&& (flag
& PATH_CHECK_ABSOLUTE
))
408 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
409 "%s= path is not absolute%s: %s",
410 lvalue
, fatal
? "" : ", ignoring", path
);
412 if (absolute
&& (flag
& PATH_CHECK_RELATIVE
))
413 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
414 "%s= path is absolute%s: %s",
415 lvalue
, fatal
? "" : ", ignoring", path
);
418 path_simplify(path
, true);
420 if (!path_is_valid(path
))
421 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
422 "%s= path has invalid length (%zu bytes)%s.",
423 lvalue
, strlen(path
), fatal
? "" : ", ignoring");
425 if (!path_is_normalized(path
))
426 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
427 "%s= path is not normalized%s: %s",
428 lvalue
, fatal
? "" : ", ignoring", path
);
433 char* path_startswith(const char *path
, const char *prefix
) {
437 /* Returns a pointer to the start of the first component after the parts matched by
439 * - both paths are absolute or both paths are relative,
441 * - each component in prefix in turn matches a component in path at the same position.
442 * An empty string will be returned when the prefix and path are equivalent.
444 * Returns NULL otherwise.
447 if ((path
[0] == '/') != (prefix
[0] == '/'))
453 path
+= strspn(path
, "/");
454 prefix
+= strspn(prefix
, "/");
462 a
= strcspn(path
, "/");
463 b
= strcspn(prefix
, "/");
468 if (memcmp(path
, prefix
, a
) != 0)
476 int path_compare(const char *a
, const char *b
) {
482 /* A relative path and an absolute path must not compare as equal.
483 * Which one is sorted before the other does not really matter.
484 * Here a relative path is ordered before an absolute path. */
485 d
= (a
[0] == '/') - (b
[0] == '/');
495 if (*a
== 0 && *b
== 0)
498 /* Order prefixes first: "/foo" before "/foo/bar" */
507 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
508 d
= memcmp(a
, b
, MIN(j
, k
));
510 return (d
> 0) - (d
< 0); /* sign of d */
512 /* Sort "/foo/a" before "/foo/aaa" */
513 d
= (j
> k
) - (j
< k
); /* sign of (j - k) */
522 bool path_equal(const char *a
, const char *b
) {
523 return path_compare(a
, b
) == 0;
526 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
527 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
530 char* path_join_internal(const char *first
, ...) {
537 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings end/begin
538 * already with one so that it is unnecessary. Note that slashes which are already duplicate won't be
539 * removed. The string returned is hence always equal to or longer than the sum of the lengths of each
542 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of which some
547 * path_join("foo", "bar") → "foo/bar"
548 * path_join("foo/", "bar") → "foo/bar"
549 * path_join("", "foo", "", "bar", "") → "foo/bar" */
551 sz
= strlen_ptr(first
);
553 while ((p
= va_arg(ap
, char*)) != POINTER_MAX
)
558 joined
= new(char, sz
+ 1);
562 if (!isempty(first
)) {
563 q
= stpcpy(joined
, first
);
564 slash
= endswith(first
, "/");
566 /* Skip empty items */
569 slash
= true; /* no need to generate a slash anymore */
573 while ((p
= va_arg(ap
, char*)) != POINTER_MAX
) {
577 if (!slash
&& p
[0] != '/')
581 slash
= endswith(p
, "/");
588 static int check_x_access(const char *path
, int *ret_fd
) {
590 _cleanup_close_
int fd
= -1;
593 /* We need to use O_PATH because there may be executables for which we have only exec
594 * permissions, but not read (usually suid executables). */
595 fd
= open(path
, O_PATH
|O_CLOEXEC
);
599 r
= access_fd(fd
, X_OK
);
603 *ret_fd
= TAKE_FD(fd
);
605 /* Let's optimize things a bit by not opening the file if we don't need the fd. */
606 if (access(path
, X_OK
) < 0)
613 int find_executable_full(const char *name
, bool use_path_envvar
, char **ret_filename
, int *ret_fd
) {
615 const char *p
= NULL
;
620 _cleanup_close_
int fd
= -1;
622 r
= check_x_access(name
, ret_fd
? &fd
: NULL
);
627 r
= path_make_absolute_cwd(name
, ret_filename
);
633 *ret_fd
= TAKE_FD(fd
);
639 /* Plain getenv, not secure_getenv, because we want to actually allow the user to pick the
645 last_error
= -ENOENT
;
647 /* Resolve a single-component name to a full path */
649 _cleanup_free_
char *j
= NULL
, *element
= NULL
;
650 _cleanup_close_
int fd
= -1;
652 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
658 if (!path_is_absolute(element
))
661 j
= path_join(element
, name
);
665 r
= check_x_access(j
, ret_fd
? &fd
: NULL
);
667 _cleanup_free_
char *with_dash
;
669 with_dash
= strjoin(j
, "/");
673 /* If this passes, it must be a directory, and so should be skipped. */
674 if (access(with_dash
, X_OK
) >= 0)
677 /* We can't just `continue` inverting this case, since we need to update last_error. */
678 if (errno
== ENOTDIR
) {
681 *ret_filename
= path_simplify(TAKE_PTR(j
), false);
683 *ret_fd
= TAKE_FD(fd
);
689 /* PATH entries which we don't have access to are ignored, as per tradition. */
697 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
698 bool changed
= false;
699 const char* const* i
;
706 STRV_FOREACH(i
, paths
) {
710 if (stat(*i
, &stats
) < 0)
713 u
= timespec_load(&stats
.st_mtim
);
719 log_debug("timestamp of '%s' changed", *i
);
721 /* update timestamp */
732 static int executable_is_good(const char *executable
) {
733 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
736 r
= find_executable(executable
, &p
);
742 /* An fsck that is linked to /bin/true is a non-existent fsck */
744 r
= readlink_malloc(p
, &d
);
745 if (r
== -EINVAL
) /* not a symlink */
750 return !PATH_IN_SET(d
, "true"
756 int fsck_exists(const char *fstype
) {
761 if (streq(fstype
, "auto"))
764 checker
= strjoina("fsck.", fstype
);
765 return executable_is_good(checker
);
768 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
773 * This function is intended to be used in command line
774 * parsers, to handle paths that are passed in. It makes the
775 * path absolute, and reduces it to NULL if omitted or
776 * root (the latter optionally).
778 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
779 * SUCCESS! Hence, do not pass in uninitialized pointers.
787 r
= path_make_absolute_cwd(path
, &p
);
789 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
791 path_simplify(p
, false);
792 if (suppress_root
&& empty_or_root(p
))
795 free_and_replace(*arg
, p
);
800 char* dirname_malloc(const char *path
) {
801 char *d
, *dir
, *dir2
;
821 const char *last_path_component(const char *path
) {
823 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
836 * Also, the empty string is mapped to itself.
838 * This is different than basename(), which returns "" when a trailing slash is present.
846 l
= k
= strlen(path
);
847 if (l
== 0) /* special case — an empty string */
850 while (k
> 0 && path
[k
-1] == '/')
853 if (k
== 0) /* the root directory */
856 while (k
> 0 && path
[k
-1] != '/')
862 int path_extract_filename(const char *p
, char **ret
) {
863 _cleanup_free_
char *a
= NULL
;
864 const char *c
, *e
= NULL
, *q
;
866 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
867 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing slashes. */
872 c
= last_path_component(p
);
874 for (q
= c
; *q
!= 0; q
++)
878 if (!e
) /* no valid character? */
881 a
= strndup(c
, e
- c
);
885 if (!filename_is_valid(a
))
893 bool filename_is_valid(const char *p
) {
899 if (dot_or_dot_dot(p
))
902 e
= strchrnul(p
, '/');
906 if (e
- p
> FILENAME_MAX
) /* FILENAME_MAX is counted *without* the trailing NUL byte */
912 bool path_is_valid(const char *p
) {
917 if (strlen(p
) >= PATH_MAX
) /* PATH_MAX is counted *with* the trailing NUL byte */
923 bool path_is_normalized(const char *p
) {
925 if (!path_is_valid(p
))
928 if (dot_or_dot_dot(p
))
931 if (startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
934 if (startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
943 char *file_in_same_dir(const char *path
, const char *filename
) {
950 /* This removes the last component of path and appends
951 * filename, unless the latter is absolute anyway or the
954 if (path_is_absolute(filename
))
955 return strdup(filename
);
957 e
= strrchr(path
, '/');
959 return strdup(filename
);
961 k
= strlen(filename
);
962 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
966 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
970 bool hidden_or_backup_file(const char *filename
) {
975 if (filename
[0] == '.' ||
976 streq(filename
, "lost+found") ||
977 streq(filename
, "aquota.user") ||
978 streq(filename
, "aquota.group") ||
979 endswith(filename
, "~"))
982 p
= strrchr(filename
, '.');
986 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
987 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
988 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
989 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
990 * string. Specifically: there's now:
992 * The generic suffixes "~" and ".bak" for backup files
993 * The generic prefix "." for hidden files
995 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
996 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
999 return STR_IN_SET(p
+ 1,
1019 bool is_device_path(const char *path
) {
1021 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
1023 return PATH_STARTSWITH_SET(path
, "/dev/", "/sys/");
1026 bool valid_device_node_path(const char *path
) {
1028 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
1029 * actual device node. */
1031 if (!PATH_STARTSWITH_SET(path
, "/dev/", "/run/systemd/inaccessible/"))
1034 if (endswith(path
, "/")) /* can't be a device node if it ends in a slash */
1037 return path_is_normalized(path
);
1040 bool valid_device_allow_pattern(const char *path
) {
1043 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
1046 if (STARTSWITH_SET(path
, "block-", "char-"))
1049 return valid_device_node_path(path
);
1052 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
1053 const char *pattern
;
1056 /* Try to guess if systemd installation is later than the specified version. This
1057 * is hacky and likely to yield false negatives, particularly if the installation
1058 * is non-standard. False positives should be relatively rare.
1061 NULSTR_FOREACH(pattern
,
1062 /* /lib works for systems without usr-merge, and for systems with a sane
1063 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
1064 * for Gentoo which does a merge without making /lib a symlink.
1066 "lib/systemd/libsystemd-shared-*.so\0"
1067 "lib64/systemd/libsystemd-shared-*.so\0"
1068 "usr/lib/systemd/libsystemd-shared-*.so\0"
1069 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
1071 _cleanup_strv_free_
char **names
= NULL
;
1072 _cleanup_free_
char *path
= NULL
;
1075 path
= path_join(root
, pattern
);
1079 r
= glob_extend(&names
, path
, 0);
1085 assert_se(c
= endswith(path
, "*.so"));
1086 *c
= '\0'; /* truncate the glob part */
1088 STRV_FOREACH(name
, names
) {
1089 /* This is most likely to run only once, hence let's not optimize anything. */
1093 t
= startswith(*name
, path
);
1097 t2
= endswith(t
, ".so");
1101 t2
[0] = '\0'; /* truncate the suffix */
1103 r
= safe_atou(t
, &version
);
1105 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
1109 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1111 version
>= minimal_version
? "OK" : "too old");
1112 if (version
>= minimal_version
)
1120 bool dot_or_dot_dot(const char *path
) {
1130 return path
[2] == 0;
1133 bool empty_or_root(const char *root
) {
1135 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1136 * i.e. either / or NULL or the empty string or any equivalent. */
1141 return root
[strspn(root
, "/")] == 0;
1144 bool path_strv_contains(char **l
, const char *path
) {
1148 if (path_equal(*i
, path
))
1154 bool prefixed_path_strv_contains(char **l
, const char *path
) {
1157 STRV_FOREACH(i
, l
) {
1163 if (path_equal(j
, path
))
1170 bool credential_name_valid(const char *s
) {
1171 /* We want that credential names are both valid in filenames (since that's our primary way to pass
1172 * them around) and as fdnames (which is how we might want to pass them around eventually) */
1173 return filename_is_valid(s
) && fdname_is_valid(s
);