1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
10 #include "alloc-util.h"
11 #include "chase-symlinks.h"
12 #include "extract-word.h"
15 #include "glob-util.h"
18 #include "path-util.h"
19 #include "stat-util.h"
20 #include "string-util.h"
22 #include "time-util.h"
24 int path_split_and_make_absolute(const char *p
, char ***ret
) {
31 l
= strv_split(p
, ":");
35 r
= path_strv_make_absolute_cwd(l
);
45 char *path_make_absolute(const char *p
, const char *prefix
) {
48 /* Makes every item in the list an absolute path by prepending
49 * the prefix, if specified and necessary */
51 if (path_is_absolute(p
) || isempty(prefix
))
54 return path_join(prefix
, p
);
57 int safe_getcwd(char **ret
) {
58 _cleanup_free_
char *cwd
= NULL
;
60 cwd
= get_current_dir_name();
62 return negative_errno();
64 /* Let's make sure the directory is really absolute, to protect us from the logic behind
75 int path_make_absolute_cwd(const char *p
, char **ret
) {
82 /* Similar to path_make_absolute(), but prefixes with the
83 * current working directory. */
85 if (path_is_absolute(p
))
88 _cleanup_free_
char *cwd
= NULL
;
90 r
= safe_getcwd(&cwd
);
94 c
= path_join(cwd
, p
);
103 int path_make_relative(const char *from
, const char *to
, char **ret
) {
104 _cleanup_free_
char *result
= NULL
;
114 /* Strips the common part, and adds ".." elements as necessary. */
116 if (!path_is_absolute(from
) || !path_is_absolute(to
))
120 r
= path_find_first_component(&from
, true, &f
);
124 k
= path_find_first_component(&to
, true, &t
);
131 /* from and to are equivalent. */
132 result
= strdup(".");
136 /* 'to' is inside of 'from'. */
141 path_simplify(result
);
143 if (!path_is_valid(result
))
147 *ret
= TAKE_PTR(result
);
151 if (r
!= k
|| !strneq(f
, t
, r
))
155 /* If we're here, then "from_dir" has one or more elements that need to
156 * be replaced with "..". */
158 for (n_parents
= 1;; n_parents
++) {
159 /* If this includes ".." we can't do a simple series of "..". */
160 r
= path_find_first_component(&from
, false, &f
);
167 if (isempty(t
) && n_parents
* 3 > PATH_MAX
)
168 /* PATH_MAX is counted *with* the trailing NUL byte */
171 result
= new(char, n_parents
* 3 + !isempty(t
) + strlen_ptr(t
));
175 for (p
= result
; n_parents
> 0; n_parents
--)
176 p
= mempcpy(p
, "../", 3);
179 /* Remove trailing slash and terminate string. */
181 *ret
= TAKE_PTR(result
);
187 path_simplify(result
);
189 if (!path_is_valid(result
))
192 *ret
= TAKE_PTR(result
);
196 int path_make_relative_parent(const char *from_child
, const char *to
, char **ret
) {
197 _cleanup_free_
char *from
= NULL
;
204 /* Similar to path_make_relative(), but provides the relative path from the parent directory of
205 * 'from_child'. This may be useful when creating relative symlink. */
207 r
= path_extract_directory(from_child
, &from
);
211 return path_make_relative(from
, to
, ret
);
214 char* path_startswith_strv(const char *p
, char **set
) {
215 STRV_FOREACH(s
, set
) {
218 t
= path_startswith(p
, *s
);
226 int path_strv_make_absolute_cwd(char **l
) {
229 /* Goes through every item in the string list and makes it
230 * absolute. This works in place and won't rollback any
231 * changes on failure. */
236 r
= path_make_absolute_cwd(*s
, &t
);
241 free_and_replace(*s
, t
);
247 char **path_strv_resolve(char **l
, const char *root
) {
255 /* Goes through every item in the string list and canonicalize
256 * the path. This works in place and won't rollback any
257 * changes on failure. */
260 _cleanup_free_
char *orig
= NULL
;
263 if (!path_is_absolute(*s
)) {
270 t
= path_join(root
, orig
);
278 r
= chase_symlinks(t
, root
, 0, &u
, NULL
);
296 x
= path_startswith(u
, root
);
298 /* restore the slash if it was lost */
299 if (!startswith(x
, "/"))
310 /* canonicalized path goes outside of
311 * prefix, keep the original path instead */
312 free_and_replace(u
, orig
);
328 char **path_strv_resolve_uniq(char **l
, const char *root
) {
333 if (!path_strv_resolve(l
, root
))
339 char *path_simplify(char *path
) {
340 bool add_slash
= false;
346 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots.
347 * Modifies the passed string in-place.
349 * ///foo//./bar/. becomes /foo/bar
350 * .//./foo//./bar/. becomes foo/bar
356 if (path_is_absolute(path
))
359 for (const char *p
= f
;;) {
362 r
= path_find_first_component(&p
, true, &e
);
370 /* if path is invalid, then refuse to simplify remaining part. */
371 memmove(f
, p
, strlen(p
) + 1);
381 /* Special rule, if we stripped everything, we need a "." for the current directory. */
389 char *path_startswith_full(const char *path
, const char *prefix
, bool accept_dot_dot
) {
393 /* Returns a pointer to the start of the first component after the parts matched by
395 * - both paths are absolute or both paths are relative,
397 * - each component in prefix in turn matches a component in path at the same position.
398 * An empty string will be returned when the prefix and path are equivalent.
400 * Returns NULL otherwise.
403 if ((path
[0] == '/') != (prefix
[0] == '/'))
410 r
= path_find_first_component(&path
, accept_dot_dot
, &p
);
414 k
= path_find_first_component(&prefix
, accept_dot_dot
, &q
);
419 return (char*) (p
?: path
);
424 if (!strneq(p
, q
, r
))
429 int path_compare(const char *a
, const char *b
) {
432 /* Order NULL before non-NULL */
437 /* A relative path and an absolute path must not compare as equal.
438 * Which one is sorted before the other does not really matter.
439 * Here a relative path is ordered before an absolute path. */
440 r
= CMP(path_is_absolute(a
), path_is_absolute(b
));
448 j
= path_find_first_component(&a
, true, &aa
);
449 k
= path_find_first_component(&b
, true, &bb
);
451 if (j
< 0 || k
< 0) {
452 /* When one of paths is invalid, order invalid path after valid one. */
453 r
= CMP(j
< 0, k
< 0);
457 /* fallback to use strcmp() if both paths are invalid. */
461 /* Order prefixes first: "/foo" before "/foo/bar" */
470 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
471 r
= memcmp(aa
, bb
, MIN(j
, k
));
475 /* Sort "/foo/a" before "/foo/aaa" */
482 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
483 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
486 bool path_equal_filename(const char *a
, const char *b
) {
487 _cleanup_free_
char *a_basename
= NULL
, *b_basename
= NULL
;
493 r
= path_extract_filename(a
, &a_basename
);
495 log_debug_errno(r
, "Failed to parse basename of %s: %m", a
);
498 r
= path_extract_filename(b
, &b_basename
);
500 log_debug_errno(r
, "Failed to parse basename of %s: %m", b
);
504 return path_equal(a_basename
, b_basename
);
507 char* path_extend_internal(char **x
, ...) {
514 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings end/begin
515 * already with one so that it is unnecessary. Note that slashes which are already duplicate won't be
516 * removed. The string returned is hence always equal to or longer than the sum of the lengths of each
519 * The first argument may be an already allocated string that is extended via realloc() if
520 * non-NULL. path_extend() and path_join() are macro wrappers around this function, making use of the
521 * first parameter to distinguish the two operations.
523 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of which some
528 * path_join("foo", "bar") → "foo/bar"
529 * path_join("foo/", "bar") → "foo/bar"
530 * path_join("", "foo", "", "bar", "") → "foo/bar" */
532 sz
= old_sz
= x
? strlen_ptr(*x
) : 0;
534 while ((p
= va_arg(ap
, char*)) != POINTER_MAX
) {
541 if (sz
> SIZE_MAX
- add
) { /* overflow check */
550 nx
= realloc(x
? *x
: NULL
, GREEDY_ALLOC_ROUND_UP(sz
+1));
557 slash
= nx
[old_sz
-1] == '/';
560 slash
= true; /* no need to generate a slash anymore */
566 while ((p
= va_arg(ap
, char*)) != POINTER_MAX
) {
570 if (!slash
&& p
[0] != '/')
574 slash
= endswith(p
, "/");
581 static int check_x_access(const char *path
, int *ret_fd
) {
582 _cleanup_close_
int fd
= -1;
585 /* We need to use O_PATH because there may be executables for which we have only exec
586 * permissions, but not read (usually suid executables). */
587 fd
= open(path
, O_PATH
|O_CLOEXEC
);
591 r
= fd_verify_regular(fd
);
595 r
= access_fd(fd
, X_OK
);
597 /* /proc is not mounted. Fallback to access(). */
598 if (access(path
, X_OK
) < 0)
604 *ret_fd
= TAKE_FD(fd
);
609 static int find_executable_impl(const char *name
, const char *root
, char **ret_filename
, int *ret_fd
) {
610 _cleanup_close_
int fd
= -1;
611 _cleanup_free_
char *path_name
= NULL
;
616 /* Function chase_symlinks() is invoked only when root is not NULL, as using it regardless of
617 * root value would alter the behavior of existing callers for example: /bin/sleep would become
618 * /usr/bin/sleep when find_executables is called. Hence, this function should be invoked when
619 * needed to avoid unforeseen regression or other complicated changes. */
621 r
= chase_symlinks(name
,
625 /* ret_fd= */ NULL
); /* prefix root to name in case full paths are not specified */
632 r
= check_x_access(name
, ret_fd
? &fd
: NULL
);
637 r
= path_make_absolute_cwd(name
, ret_filename
);
643 *ret_fd
= TAKE_FD(fd
);
648 int find_executable_full(const char *name
, const char *root
, char **exec_search_path
, bool use_path_envvar
, char **ret_filename
, int *ret_fd
) {
649 int last_error
= -ENOENT
, r
= 0;
650 const char *p
= NULL
;
655 return find_executable_impl(name
, root
, ret_filename
, ret_fd
);
658 /* Plain getenv, not secure_getenv, because we want to actually allow the user to pick the
664 if (exec_search_path
) {
665 STRV_FOREACH(element
, exec_search_path
) {
666 _cleanup_free_
char *full_path
= NULL
;
668 if (!path_is_absolute(*element
))
671 full_path
= path_join(*element
, name
);
675 r
= find_executable_impl(full_path
, root
, ret_filename
, ret_fd
);
686 /* Resolve a single-component name to a full path */
688 _cleanup_free_
char *element
= NULL
;
690 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
696 if (!path_is_absolute(element
))
699 if (!path_extend(&element
, name
))
702 r
= find_executable_impl(element
, root
, ret_filename
, ret_fd
);
704 /* PATH entries which we don't have access to are ignored, as per tradition. */
717 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
718 bool changed
= false, originally_unset
;
725 originally_unset
= *timestamp
== 0;
727 STRV_FOREACH(i
, paths
) {
731 if (stat(*i
, &stats
) < 0)
734 u
= timespec_load(&stats
.st_mtim
);
740 log_debug(originally_unset
? "Loaded timestamp for '%s'." : "Timestamp of '%s' changed.", *i
);
742 /* update timestamp */
753 static int executable_is_good(const char *executable
) {
754 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
757 r
= find_executable(executable
, &p
);
763 /* An fsck that is linked to /bin/true is a non-existent fsck */
765 r
= readlink_malloc(p
, &d
);
766 if (r
== -EINVAL
) /* not a symlink */
771 return !PATH_IN_SET(d
, "true"
777 int fsck_exists(const char *fstype
) {
782 if (streq(fstype
, "auto"))
785 checker
= strjoina("fsck.", fstype
);
786 return executable_is_good(checker
);
789 static const char *skip_slash_or_dot(const char *p
) {
790 for (; !isempty(p
); p
++) {
793 if (startswith(p
, "./")) {
802 int path_find_first_component(const char **p
, bool accept_dot_dot
, const char **ret
) {
803 const char *q
, *first
, *end_first
, *next
;
808 /* When a path is input, then returns the pointer to the first component and its length, and
809 * move the input pointer to the next component or nul. This skips both over any '/'
810 * immediately *before* and *after* the first component before returning.
813 * Input: p: "//.//aaa///bbbbb/cc"
814 * Output: p: "bbbbb///cc"
815 * ret: "aaa///bbbbb/cc"
816 * return value: 3 (== strlen("aaa"))
819 * Output: p: (pointer to NUL)
821 * return value: 3 (== strlen("aaa"))
823 * Input: p: "/", ".", ""
824 * Output: p: (pointer to NUL)
833 * Input: p: "(too long component)"
834 * Output: return value: -EINVAL
836 * (when accept_dot_dot is false)
837 * Input: p: "//..//aaa///bbbbb/cc"
838 * Output: return value: -EINVAL
843 first
= skip_slash_or_dot(q
);
844 if (isempty(first
)) {
850 if (streq(first
, ".")) {
857 end_first
= strchrnul(first
, '/');
858 len
= end_first
- first
;
862 if (!accept_dot_dot
&& len
== 2 && first
[0] == '.' && first
[1] == '.')
865 next
= skip_slash_or_dot(end_first
);
867 *p
= next
+ streq(next
, ".");
873 static const char *skip_slash_or_dot_backward(const char *path
, const char *q
) {
875 assert(!q
|| q
>= path
);
877 for (; q
; q
= PTR_SUB1(q
, path
)) {
880 if (q
> path
&& strneq(q
- 1, "/.", 2))
887 int path_find_last_component(const char *path
, bool accept_dot_dot
, const char **next
, const char **ret
) {
888 const char *q
, *last_end
, *last_begin
;
891 /* Similar to path_find_first_component(), but search components from the end.
894 * Input: path: "//.//aaa///bbbbb/cc//././"
896 * Output: next: "/cc//././"
898 * return value: 2 (== strlen("cc"))
900 * Input: path: "//.//aaa///bbbbb/cc//././"
902 * Output: next: "///bbbbb/cc//././"
903 * ret: "bbbbb/cc//././"
904 * return value: 5 (== strlen("bbbbb"))
906 * Input: path: "/", ".", "", or NULL
907 * Output: next: equivalent to path
911 * Input: path: "(too long component)"
912 * Output: return value: -EINVAL
914 * (when accept_dot_dot is false)
915 * Input: path: "//..//aaa///bbbbb/cc/..//"
916 * Output: return value: -EINVAL
928 if (*next
< path
|| *next
> path
+ strlen(path
))
935 if (!IN_SET(**next
, '\0', '/'))
939 q
= path
+ strlen(path
) - 1;
941 q
= skip_slash_or_dot_backward(path
, q
);
942 if (!q
|| /* the root directory */
943 (q
== path
&& *q
== '.')) { /* path is "." or "./" */
953 while (q
&& *q
!= '/')
954 q
= PTR_SUB1(q
, path
);
956 last_begin
= q
? q
+ 1 : path
;
957 len
= last_end
- last_begin
;
961 if (!accept_dot_dot
&& len
== 2 && strneq(last_begin
, "..", 2))
965 q
= skip_slash_or_dot_backward(path
, q
);
966 *next
= q
? q
+ 1 : path
;
974 const char *last_path_component(const char *path
) {
976 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
989 * Also, the empty string is mapped to itself.
991 * This is different than basename(), which returns "" when a trailing slash is present.
993 * This always succeeds (except if you pass NULL in which case it returns NULL, too).
1001 l
= k
= strlen(path
);
1002 if (l
== 0) /* special case — an empty string */
1005 while (k
> 0 && path
[k
-1] == '/')
1008 if (k
== 0) /* the root directory */
1009 return path
+ l
- 1;
1011 while (k
> 0 && path
[k
-1] != '/')
1017 int path_extract_filename(const char *path
, char **ret
) {
1018 _cleanup_free_
char *a
= NULL
;
1019 const char *c
, *next
= NULL
;
1022 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
1023 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing
1026 * -EINVAL → if the path is not valid
1027 * -EADDRNOTAVAIL → if only a directory was specified, but no filename, i.e. the root dir
1028 * itself or "." is specified
1029 * -ENOMEM → no memory
1031 * Returns >= 0 on success. If the input path has a trailing slash, returns O_DIRECTORY, to
1032 * indicate the referenced file must be a directory.
1034 * This function guarantees to return a fully valid filename, i.e. one that passes
1035 * filename_is_valid() – this means "." and ".." are not accepted. */
1037 if (!path_is_valid(path
))
1040 r
= path_find_last_component(path
, false, &next
, &c
);
1043 if (r
== 0) /* root directory */
1044 return -EADDRNOTAVAIL
;
1051 return strlen(c
) > (size_t) r
? O_DIRECTORY
: 0;
1054 int path_extract_directory(const char *path
, char **ret
) {
1055 _cleanup_free_
char *a
= NULL
;
1056 const char *c
, *next
= NULL
;
1059 /* The inverse of path_extract_filename(), i.e. returns the directory path prefix. Returns:
1061 * -EINVAL → if the path is not valid
1062 * -EDESTADDRREQ → if no directory was specified in the passed in path, i.e. only a filename was passed
1063 * -EADDRNOTAVAIL → if the passed in parameter had no filename but did have a directory, i.e.
1064 * the root dir itself or "." was specified
1065 * -ENOMEM → no memory (surprise!)
1067 * This function guarantees to return a fully valid path, i.e. one that passes path_is_valid().
1070 r
= path_find_last_component(path
, false, &next
, &c
);
1073 if (r
== 0) /* empty or root */
1074 return isempty(path
) ? -EINVAL
: -EADDRNOTAVAIL
;
1076 if (*path
!= '/') /* filename only */
1077 return -EDESTADDRREQ
;
1086 a
= strndup(path
, next
- path
);
1092 if (!path_is_valid(a
))
1099 bool filename_is_valid(const char *p
) {
1105 if (dot_or_dot_dot(p
)) /* Yes, in this context we consider "." and ".." invalid */
1108 e
= strchrnul(p
, '/');
1112 if (e
- p
> NAME_MAX
) /* NAME_MAX is counted *without* the trailing NUL byte */
1118 bool path_is_valid_full(const char *p
, bool accept_dot_dot
) {
1122 for (const char *e
= p
;;) {
1125 r
= path_find_first_component(&e
, accept_dot_dot
, NULL
);
1129 if (e
- p
>= PATH_MAX
) /* Already reached the maximum length for a path? (PATH_MAX is counted
1130 * *with* the trailing NUL byte) */
1132 if (*e
== 0) /* End of string? Yay! */
1137 bool path_is_normalized(const char *p
) {
1138 if (!path_is_safe(p
))
1141 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
1144 if (strstr(p
, "//"))
1150 char *file_in_same_dir(const char *path
, const char *filename
) {
1157 /* This removes the last component of path and appends
1158 * filename, unless the latter is absolute anyway or the
1161 if (path_is_absolute(filename
))
1162 return strdup(filename
);
1164 e
= strrchr(path
, '/');
1166 return strdup(filename
);
1168 k
= strlen(filename
);
1169 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
1173 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
1177 bool hidden_or_backup_file(const char *filename
) {
1180 if (filename
[0] == '.' ||
1181 STR_IN_SET(filename
,
1185 endswith(filename
, "~"))
1188 const char *dot
= strrchr(filename
, '.');
1192 /* Please, let's not add more entries to the list below. If external projects think it's a good idea
1193 * to come up with always new suffixes and that everybody else should just adjust to that, then it
1194 * really should be on them. Hence, in future, let's not add any more entries. Instead, let's ask
1195 * those packages to instead adopt one of the generic suffixes/prefixes for hidden files or backups,
1196 * possibly augmented with an additional string. Specifically: there's now:
1198 * The generic suffixes "~" and ".bak" for backup files
1199 * The generic prefix "." for hidden files
1201 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old",
1202 * ".foopkg-dist" or so registered, let's refuse that and ask them to use ".foopkg.new",
1203 * ".foopkg.old" or ".foopkg~" instead.
1206 return STR_IN_SET(dot
+ 1,
1226 bool is_device_path(const char *path
) {
1228 /* Returns true for paths that likely refer to a device, either by path in sysfs or to something in
1231 return PATH_STARTSWITH_SET(path
, "/dev/", "/sys/");
1234 bool valid_device_node_path(const char *path
) {
1236 /* Some superficial checks whether the specified path is a valid device node path, all without
1237 * looking at the actual device node. */
1239 if (!PATH_STARTSWITH_SET(path
, "/dev/", "/run/systemd/inaccessible/"))
1242 if (endswith(path
, "/")) /* can't be a device node if it ends in a slash */
1245 return path_is_normalized(path
);
1248 bool valid_device_allow_pattern(const char *path
) {
1251 /* Like valid_device_node_path(), but also allows full-subsystem expressions like those accepted by
1252 * DeviceAllow= and DeviceDeny=. */
1254 if (STARTSWITH_SET(path
, "block-", "char-"))
1257 return valid_device_node_path(path
);
1260 bool dot_or_dot_dot(const char *path
) {
1270 return path
[2] == 0;
1273 bool empty_or_root(const char *path
) {
1275 /* For operations relative to some root directory, returns true if the specified root directory is
1276 * redundant, i.e. either / or NULL or the empty string or any equivalent. */
1281 return path_equal(path
, "/");
1284 bool path_strv_contains(char **l
, const char *path
) {
1286 if (path_equal(*i
, path
))
1292 bool prefixed_path_strv_contains(char **l
, const char *path
) {
1293 STRV_FOREACH(i
, l
) {
1300 if (path_equal(j
, path
))
1307 int path_glob_can_match(const char *pattern
, const char *prefix
, char **ret
) {
1311 for (const char *a
= pattern
, *b
= prefix
;;) {
1312 _cleanup_free_
char *g
= NULL
, *h
= NULL
;
1316 r
= path_find_first_component(&a
, /* accept_dot_dot = */ false, &p
);
1320 s
= path_find_first_component(&b
, /* accept_dot_dot = */ false, &q
);
1325 /* The pattern matches the prefix. */
1329 t
= path_join(prefix
, p
);
1341 if (r
== s
&& strneq(p
, q
, r
))
1342 continue; /* common component. Check next. */
1348 if (!string_is_glob(g
))
1351 /* We found a glob component. Check if the glob pattern matches the prefix component. */
1357 r
= fnmatch(g
, h
, 0);
1358 if (r
== FNM_NOMATCH
)
1360 if (r
!= 0) /* Failure to process pattern? */
1364 /* The pattern does not match the prefix. */