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 "chase-symlinks.h"
17 #include "extract-word.h"
22 #include "path-util.h"
23 #include "stat-util.h"
24 #include "string-util.h"
26 #include "time-util.h"
28 int path_split_and_make_absolute(const char *p
, char ***ret
) {
35 l
= strv_split(p
, ":");
39 r
= path_strv_make_absolute_cwd(l
);
49 char *path_make_absolute(const char *p
, const char *prefix
) {
52 /* Makes every item in the list an absolute path by prepending
53 * the prefix, if specified and necessary */
55 if (path_is_absolute(p
) || isempty(prefix
))
58 return path_join(prefix
, p
);
61 int safe_getcwd(char **ret
) {
62 _cleanup_free_
char *cwd
= NULL
;
64 cwd
= get_current_dir_name();
66 return negative_errno();
68 /* Let's make sure the directory is really absolute, to protect us from the logic behind
79 int path_make_absolute_cwd(const char *p
, char **ret
) {
86 /* Similar to path_make_absolute(), but prefixes with the
87 * current working directory. */
89 if (path_is_absolute(p
))
92 _cleanup_free_
char *cwd
= NULL
;
94 r
= safe_getcwd(&cwd
);
98 c
= path_join(cwd
, p
);
107 int path_make_relative(const char *from
, const char *to
, char **ret
) {
108 _cleanup_free_
char *result
= NULL
;
118 /* Strips the common part, and adds ".." elements as necessary. */
120 if (!path_is_absolute(from
) || !path_is_absolute(to
))
124 r
= path_find_first_component(&from
, true, &f
);
128 k
= path_find_first_component(&to
, true, &t
);
135 /* from and to are equivalent. */
136 result
= strdup(".");
140 /* 'to' is inside of 'from'. */
145 path_simplify(result
);
147 if (!path_is_valid(result
))
151 *ret
= TAKE_PTR(result
);
155 if (r
!= k
|| !strneq(f
, t
, r
))
159 /* If we're here, then "from_dir" has one or more elements that need to
160 * be replaced with "..". */
162 for (n_parents
= 1;; n_parents
++) {
163 /* If this includes ".." we can't do a simple series of "..". */
164 r
= path_find_first_component(&from
, false, &f
);
171 if (isempty(t
) && n_parents
* 3 > PATH_MAX
)
172 /* PATH_MAX is counted *with* the trailing NUL byte */
175 result
= new(char, n_parents
* 3 + !isempty(t
) + strlen_ptr(t
));
179 for (p
= result
; n_parents
> 0; n_parents
--)
180 p
= mempcpy(p
, "../", 3);
183 /* Remove trailing slash and terminate string. */
185 *ret
= TAKE_PTR(result
);
191 path_simplify(result
);
193 if (!path_is_valid(result
))
196 *ret
= TAKE_PTR(result
);
200 char* path_startswith_strv(const char *p
, char **set
) {
201 STRV_FOREACH(s
, set
) {
204 t
= path_startswith(p
, *s
);
212 int path_strv_make_absolute_cwd(char **l
) {
215 /* Goes through every item in the string list and makes it
216 * absolute. This works in place and won't rollback any
217 * changes on failure. */
222 r
= path_make_absolute_cwd(*s
, &t
);
227 free_and_replace(*s
, t
);
233 char **path_strv_resolve(char **l
, const char *root
) {
241 /* Goes through every item in the string list and canonicalize
242 * the path. This works in place and won't rollback any
243 * changes on failure. */
246 _cleanup_free_
char *orig
= NULL
;
249 if (!path_is_absolute(*s
)) {
256 t
= path_join(root
, orig
);
264 r
= chase_symlinks(t
, root
, 0, &u
, NULL
);
282 x
= path_startswith(u
, root
);
284 /* restore the slash if it was lost */
285 if (!startswith(x
, "/"))
296 /* canonicalized path goes outside of
297 * prefix, keep the original path instead */
298 free_and_replace(u
, orig
);
314 char **path_strv_resolve_uniq(char **l
, const char *root
) {
319 if (!path_strv_resolve(l
, root
))
325 char *path_simplify(char *path
) {
326 bool add_slash
= false;
332 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots.
333 * Modifies the passed string in-place.
335 * ///foo//./bar/. becomes /foo/bar
336 * .//./foo//./bar/. becomes foo/bar
342 if (path_is_absolute(path
))
345 for (const char *p
= f
;;) {
348 r
= path_find_first_component(&p
, true, &e
);
356 /* if path is invalid, then refuse to simplify remaining part. */
357 memmove(f
, p
, strlen(p
) + 1);
367 /* Special rule, if we stripped everything, we need a "." for the current directory. */
375 char *path_startswith_full(const char *path
, const char *prefix
, bool accept_dot_dot
) {
379 /* Returns a pointer to the start of the first component after the parts matched by
381 * - both paths are absolute or both paths are relative,
383 * - each component in prefix in turn matches a component in path at the same position.
384 * An empty string will be returned when the prefix and path are equivalent.
386 * Returns NULL otherwise.
389 if ((path
[0] == '/') != (prefix
[0] == '/'))
396 r
= path_find_first_component(&path
, accept_dot_dot
, &p
);
400 k
= path_find_first_component(&prefix
, accept_dot_dot
, &q
);
405 return (char*) (p
?: path
);
410 if (!strneq(p
, q
, r
))
415 int path_compare(const char *a
, const char *b
) {
418 /* Order NULL before non-NULL */
423 /* A relative path and an absolute path must not compare as equal.
424 * Which one is sorted before the other does not really matter.
425 * Here a relative path is ordered before an absolute path. */
426 r
= CMP(path_is_absolute(a
), path_is_absolute(b
));
434 j
= path_find_first_component(&a
, true, &aa
);
435 k
= path_find_first_component(&b
, true, &bb
);
437 if (j
< 0 || k
< 0) {
438 /* When one of paths is invalid, order invalid path after valid one. */
439 r
= CMP(j
< 0, k
< 0);
443 /* fallback to use strcmp() if both paths are invalid. */
447 /* Order prefixes first: "/foo" before "/foo/bar" */
456 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
457 r
= memcmp(aa
, bb
, MIN(j
, k
));
461 /* Sort "/foo/a" before "/foo/aaa" */
468 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
469 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
472 bool path_equal_filename(const char *a
, const char *b
) {
473 _cleanup_free_
char *a_basename
= NULL
, *b_basename
= NULL
;
479 r
= path_extract_filename(a
, &a_basename
);
481 log_debug_errno(r
, "Failed to parse basename of %s: %m", a
);
484 r
= path_extract_filename(b
, &b_basename
);
486 log_debug_errno(r
, "Failed to parse basename of %s: %m", b
);
490 return path_equal(a_basename
, b_basename
);
493 char* path_extend_internal(char **x
, ...) {
500 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings end/begin
501 * already with one so that it is unnecessary. Note that slashes which are already duplicate won't be
502 * removed. The string returned is hence always equal to or longer than the sum of the lengths of each
505 * The first argument may be an already allocated string that is extended via realloc() if
506 * non-NULL. path_extend() and path_join() are macro wrappers around this function, making use of the
507 * first parameter to distinguish the two operations.
509 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of which some
514 * path_join("foo", "bar") → "foo/bar"
515 * path_join("foo/", "bar") → "foo/bar"
516 * path_join("", "foo", "", "bar", "") → "foo/bar" */
518 sz
= old_sz
= x
? strlen_ptr(*x
) : 0;
520 while ((p
= va_arg(ap
, char*)) != POINTER_MAX
) {
527 if (sz
> SIZE_MAX
- add
) { /* overflow check */
536 nx
= realloc(x
? *x
: NULL
, GREEDY_ALLOC_ROUND_UP(sz
+1));
543 slash
= nx
[old_sz
-1] == '/';
546 slash
= true; /* no need to generate a slash anymore */
552 while ((p
= va_arg(ap
, char*)) != POINTER_MAX
) {
556 if (!slash
&& p
[0] != '/')
560 slash
= endswith(p
, "/");
567 static int check_x_access(const char *path
, int *ret_fd
) {
568 _cleanup_close_
int fd
= -1;
571 /* We need to use O_PATH because there may be executables for which we have only exec
572 * permissions, but not read (usually suid executables). */
573 fd
= open(path
, O_PATH
|O_CLOEXEC
);
577 r
= fd_verify_regular(fd
);
581 r
= access_fd(fd
, X_OK
);
583 /* /proc is not mounted. Fallback to access(). */
584 if (access(path
, X_OK
) < 0)
590 *ret_fd
= TAKE_FD(fd
);
595 static int find_executable_impl(const char *name
, const char *root
, char **ret_filename
, int *ret_fd
) {
596 _cleanup_close_
int fd
= -1;
597 _cleanup_free_
char *path_name
= NULL
;
602 /* Function chase_symlinks() is invoked only when root is not NULL, as using it regardless of
603 * root value would alter the behavior of existing callers for example: /bin/sleep would become
604 * /usr/bin/sleep when find_executables is called. Hence, this function should be invoked when
605 * needed to avoid unforeseen regression or other complicated changes. */
607 r
= chase_symlinks(name
,
611 /* ret_fd= */ NULL
); /* prefix root to name in case full paths are not specified */
618 r
= check_x_access(name
, ret_fd
? &fd
: NULL
);
623 r
= path_make_absolute_cwd(name
, ret_filename
);
629 *ret_fd
= TAKE_FD(fd
);
634 int find_executable_full(const char *name
, const char *root
, char **exec_search_path
, bool use_path_envvar
, char **ret_filename
, int *ret_fd
) {
635 int last_error
= -ENOENT
, r
= 0;
636 const char *p
= NULL
;
641 return find_executable_impl(name
, root
, ret_filename
, ret_fd
);
644 /* Plain getenv, not secure_getenv, because we want to actually allow the user to pick the
650 if (exec_search_path
) {
651 STRV_FOREACH(element
, exec_search_path
) {
652 _cleanup_free_
char *full_path
= NULL
;
654 if (!path_is_absolute(*element
))
657 full_path
= path_join(*element
, name
);
661 r
= find_executable_impl(full_path
, root
, ret_filename
, ret_fd
);
672 /* Resolve a single-component name to a full path */
674 _cleanup_free_
char *element
= NULL
;
676 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
682 if (!path_is_absolute(element
))
685 if (!path_extend(&element
, name
))
688 r
= find_executable_impl(element
, root
, ret_filename
, ret_fd
);
690 /* PATH entries which we don't have access to are ignored, as per tradition. */
703 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
704 bool changed
= false, originally_unset
;
711 originally_unset
= *timestamp
== 0;
713 STRV_FOREACH(i
, paths
) {
717 if (stat(*i
, &stats
) < 0)
720 u
= timespec_load(&stats
.st_mtim
);
726 log_debug(originally_unset
? "Loaded timestamp for '%s'." : "Timestamp of '%s' changed.", *i
);
728 /* update timestamp */
739 static int executable_is_good(const char *executable
) {
740 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
743 r
= find_executable(executable
, &p
);
749 /* An fsck that is linked to /bin/true is a non-existent fsck */
751 r
= readlink_malloc(p
, &d
);
752 if (r
== -EINVAL
) /* not a symlink */
757 return !PATH_IN_SET(d
, "true"
763 int fsck_exists(const char *fstype
) {
768 if (streq(fstype
, "auto"))
771 checker
= strjoina("fsck.", fstype
);
772 return executable_is_good(checker
);
775 char* dirname_malloc(const char *path
) {
776 char *d
, *dir
, *dir2
;
796 static const char *skip_slash_or_dot(const char *p
) {
797 for (; !isempty(p
); p
++) {
800 if (startswith(p
, "./")) {
809 int path_find_first_component(const char **p
, bool accept_dot_dot
, const char **ret
) {
810 const char *q
, *first
, *end_first
, *next
;
815 /* When a path is input, then returns the pointer to the first component and its length, and
816 * move the input pointer to the next component or nul. This skips both over any '/'
817 * immediately *before* and *after* the first component before returning.
820 * Input: p: "//.//aaa///bbbbb/cc"
821 * Output: p: "bbbbb///cc"
822 * ret: "aaa///bbbbb/cc"
823 * return value: 3 (== strlen("aaa"))
826 * Output: p: (pointer to NUL)
828 * return value: 3 (== strlen("aaa"))
830 * Input: p: "/", ".", ""
831 * Output: p: (pointer to NUL)
840 * Input: p: "(too long component)"
841 * Output: return value: -EINVAL
843 * (when accept_dot_dot is false)
844 * Input: p: "//..//aaa///bbbbb/cc"
845 * Output: return value: -EINVAL
850 first
= skip_slash_or_dot(q
);
851 if (isempty(first
)) {
857 if (streq(first
, ".")) {
864 end_first
= strchrnul(first
, '/');
865 len
= end_first
- first
;
869 if (!accept_dot_dot
&& len
== 2 && first
[0] == '.' && first
[1] == '.')
872 next
= skip_slash_or_dot(end_first
);
874 *p
= next
+ streq(next
, ".");
880 static const char *skip_slash_or_dot_backward(const char *path
, const char *q
) {
882 assert(!q
|| q
>= path
);
884 for (; q
; q
= PTR_SUB1(q
, path
)) {
887 if (q
> path
&& strneq(q
- 1, "/.", 2))
894 int path_find_last_component(const char *path
, bool accept_dot_dot
, const char **next
, const char **ret
) {
895 const char *q
, *last_end
, *last_begin
;
898 /* Similar to path_find_first_component(), but search components from the end.
901 * Input: path: "//.//aaa///bbbbb/cc//././"
903 * Output: next: "/cc//././"
905 * return value: 2 (== strlen("cc"))
907 * Input: path: "//.//aaa///bbbbb/cc//././"
909 * Output: next: "///bbbbb/cc//././"
910 * ret: "bbbbb/cc//././"
911 * return value: 5 (== strlen("bbbbb"))
913 * Input: path: "/", ".", "", or NULL
914 * Output: next: equivalent to path
918 * Input: path: "(too long component)"
919 * Output: return value: -EINVAL
921 * (when accept_dot_dot is false)
922 * Input: path: "//..//aaa///bbbbb/cc/..//"
923 * Output: return value: -EINVAL
935 if (*next
< path
|| *next
> path
+ strlen(path
))
942 if (!IN_SET(**next
, '\0', '/'))
946 q
= path
+ strlen(path
) - 1;
948 q
= skip_slash_or_dot_backward(path
, q
);
949 if (!q
|| /* the root directory */
950 (q
== path
&& *q
== '.')) { /* path is "." or "./" */
960 while (q
&& *q
!= '/')
961 q
= PTR_SUB1(q
, path
);
963 last_begin
= q
? q
+ 1 : path
;
964 len
= last_end
- last_begin
;
968 if (!accept_dot_dot
&& len
== 2 && strneq(last_begin
, "..", 2))
972 q
= skip_slash_or_dot_backward(path
, q
);
973 *next
= q
? q
+ 1 : path
;
981 const char *last_path_component(const char *path
) {
983 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
996 * Also, the empty string is mapped to itself.
998 * This is different than basename(), which returns "" when a trailing slash is present.
1000 * This always succeeds (except if you pass NULL in which case it returns NULL, too).
1008 l
= k
= strlen(path
);
1009 if (l
== 0) /* special case — an empty string */
1012 while (k
> 0 && path
[k
-1] == '/')
1015 if (k
== 0) /* the root directory */
1016 return path
+ l
- 1;
1018 while (k
> 0 && path
[k
-1] != '/')
1024 int path_extract_filename(const char *path
, char **ret
) {
1025 _cleanup_free_
char *a
= NULL
;
1026 const char *c
, *next
= NULL
;
1029 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
1030 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing
1033 * -EINVAL → if the path is not valid
1034 * -EADDRNOTAVAIL → if only a directory was specified, but no filename, i.e. the root dir
1035 * itself or "." is specified
1036 * -ENOMEM → no memory
1038 * Returns >= 0 on success. If the input path has a trailing slash, returns O_DIRECTORY, to
1039 * indicate the referenced file must be a directory.
1041 * This function guarantees to return a fully valid filename, i.e. one that passes
1042 * filename_is_valid() – this means "." and ".." are not accepted. */
1044 if (!path_is_valid(path
))
1047 r
= path_find_last_component(path
, false, &next
, &c
);
1050 if (r
== 0) /* root directory */
1051 return -EADDRNOTAVAIL
;
1058 return strlen(c
) > (size_t) r
? O_DIRECTORY
: 0;
1061 int path_extract_directory(const char *path
, char **ret
) {
1062 _cleanup_free_
char *a
= NULL
;
1063 const char *c
, *next
= NULL
;
1066 /* The inverse of path_extract_filename(), i.e. returns the directory path prefix. Returns:
1068 * -EINVAL → if the path is not valid
1069 * -EDESTADDRREQ → if no directory was specified in the passed in path, i.e. only a filename was passed
1070 * -EADDRNOTAVAIL → if the passed in parameter had no filename but did have a directory, i.e.
1071 * the root dir itself or "." was specified
1072 * -ENOMEM → no memory (surprise!)
1074 * This function guarantees to return a fully valid path, i.e. one that passes path_is_valid().
1077 r
= path_find_last_component(path
, false, &next
, &c
);
1080 if (r
== 0) /* empty or root */
1081 return isempty(path
) ? -EINVAL
: -EADDRNOTAVAIL
;
1083 if (*path
!= '/') /* filename only */
1084 return -EDESTADDRREQ
;
1093 a
= strndup(path
, next
- path
);
1099 if (!path_is_valid(a
))
1106 bool filename_is_valid(const char *p
) {
1112 if (dot_or_dot_dot(p
)) /* Yes, in this context we consider "." and ".." invalid */
1115 e
= strchrnul(p
, '/');
1119 if (e
- p
> NAME_MAX
) /* NAME_MAX is counted *without* the trailing NUL byte */
1125 bool path_is_valid_full(const char *p
, bool accept_dot_dot
) {
1129 for (const char *e
= p
;;) {
1132 r
= path_find_first_component(&e
, accept_dot_dot
, NULL
);
1136 if (e
- p
>= PATH_MAX
) /* Already reached the maximum length for a path? (PATH_MAX is counted
1137 * *with* the trailing NUL byte) */
1139 if (*e
== 0) /* End of string? Yay! */
1144 bool path_is_normalized(const char *p
) {
1145 if (!path_is_safe(p
))
1148 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
1151 if (strstr(p
, "//"))
1157 char *file_in_same_dir(const char *path
, const char *filename
) {
1164 /* This removes the last component of path and appends
1165 * filename, unless the latter is absolute anyway or the
1168 if (path_is_absolute(filename
))
1169 return strdup(filename
);
1171 e
= strrchr(path
, '/');
1173 return strdup(filename
);
1175 k
= strlen(filename
);
1176 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
1180 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
1184 bool hidden_or_backup_file(const char *filename
) {
1187 if (filename
[0] == '.' ||
1188 STR_IN_SET(filename
,
1192 endswith(filename
, "~"))
1195 const char *dot
= strrchr(filename
, '.');
1199 /* Please, let's not add more entries to the list below. If external projects think it's a good idea
1200 * to come up with always new suffixes and that everybody else should just adjust to that, then it
1201 * really should be on them. Hence, in future, let's not add any more entries. Instead, let's ask
1202 * those packages to instead adopt one of the generic suffixes/prefixes for hidden files or backups,
1203 * possibly augmented with an additional string. Specifically: there's now:
1205 * The generic suffixes "~" and ".bak" for backup files
1206 * The generic prefix "." for hidden files
1208 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old",
1209 * ".foopkg-dist" or so registered, let's refuse that and ask them to use ".foopkg.new",
1210 * ".foopkg.old" or ".foopkg~" instead.
1213 return STR_IN_SET(dot
+ 1,
1233 bool is_device_path(const char *path
) {
1235 /* Returns true for paths that likely refer to a device, either by path in sysfs or to something in
1238 return PATH_STARTSWITH_SET(path
, "/dev/", "/sys/");
1241 bool valid_device_node_path(const char *path
) {
1243 /* Some superficial checks whether the specified path is a valid device node path, all without
1244 * looking at the actual device node. */
1246 if (!PATH_STARTSWITH_SET(path
, "/dev/", "/run/systemd/inaccessible/"))
1249 if (endswith(path
, "/")) /* can't be a device node if it ends in a slash */
1252 return path_is_normalized(path
);
1255 bool valid_device_allow_pattern(const char *path
) {
1258 /* Like valid_device_node_path(), but also allows full-subsystem expressions like those accepted by
1259 * DeviceAllow= and DeviceDeny=. */
1261 if (STARTSWITH_SET(path
, "block-", "char-"))
1264 return valid_device_node_path(path
);
1267 bool dot_or_dot_dot(const char *path
) {
1277 return path
[2] == 0;
1280 bool empty_or_root(const char *path
) {
1282 /* For operations relative to some root directory, returns true if the specified root directory is
1283 * redundant, i.e. either / or NULL or the empty string or any equivalent. */
1288 return path_equal(path
, "/");
1291 bool path_strv_contains(char **l
, const char *path
) {
1293 if (path_equal(*i
, path
))
1299 bool prefixed_path_strv_contains(char **l
, const char *path
) {
1300 STRV_FOREACH(i
, l
) {
1307 if (path_equal(j
, path
))