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"
36 bool path_is_absolute(const char *p
) {
40 bool is_path(const char *p
) {
41 return !!strchr(p
, '/');
44 int path_split_and_make_absolute(const char *p
, char ***ret
) {
51 l
= strv_split(p
, ":");
55 r
= path_strv_make_absolute_cwd(l
);
65 char *path_make_absolute(const char *p
, const char *prefix
) {
68 /* Makes every item in the list an absolute path by prepending
69 * the prefix, if specified and necessary */
71 if (path_is_absolute(p
) || isempty(prefix
))
74 if (endswith(prefix
, "/"))
75 return strjoin(prefix
, p
);
77 return strjoin(prefix
, "/", p
);
80 int safe_getcwd(char **ret
) {
83 cwd
= get_current_dir_name();
85 return negative_errno();
87 /* Let's make sure the directory is really absolute, to protect us from the logic behind
98 int path_make_absolute_cwd(const char *p
, char **ret
) {
105 /* Similar to path_make_absolute(), but prefixes with the
106 * current working directory. */
108 if (path_is_absolute(p
))
111 _cleanup_free_
char *cwd
= NULL
;
113 r
= safe_getcwd(&cwd
);
117 if (endswith(cwd
, "/"))
120 c
= strjoin(cwd
, "/", p
);
129 int path_make_relative(const char *from_dir
, const char *to_path
, char **_r
) {
137 /* Strips the common part, and adds ".." elements as necessary. */
139 if (!path_is_absolute(from_dir
))
142 if (!path_is_absolute(to_path
))
145 /* Skip the common part. */
149 from_dir
+= strspn(from_dir
, "/");
150 to_path
+= strspn(to_path
, "/");
154 /* from_dir equals to_path. */
157 /* from_dir is a parent directory of to_path. */
162 path_kill_slashes(r
);
171 a
= strcspn(from_dir
, "/");
172 b
= strcspn(to_path
, "/");
177 if (memcmp(from_dir
, to_path
, a
) != 0)
184 /* If we're here, then "from_dir" has one or more elements that need to
185 * be replaced with "..". */
187 /* Count the number of necessary ".." elements. */
188 for (n_parents
= 0;;) {
191 from_dir
+= strspn(from_dir
, "/");
196 w
= strcspn(from_dir
, "/");
198 /* If this includes ".." we can't do a simple series of "..", refuse */
199 if (w
== 2 && from_dir
[0] == '.' && from_dir
[1] == '.')
202 /* Count number of elements, except if they are "." */
203 if (w
!= 1 || from_dir
[0] != '.')
209 r
= new(char, n_parents
* 3 + strlen(to_path
) + 1);
213 for (p
= r
; n_parents
> 0; n_parents
--)
214 p
= mempcpy(p
, "../", 3);
217 path_kill_slashes(r
);
223 int path_strv_make_absolute_cwd(char **l
) {
227 /* Goes through every item in the string list and makes it
228 * absolute. This works in place and won't rollback any
229 * changes on failure. */
234 r
= path_make_absolute_cwd(*s
, &t
);
238 path_kill_slashes(t
);
239 free_and_replace(*s
, t
);
245 char **path_strv_resolve(char **l
, const char *root
) {
254 /* Goes through every item in the string list and canonicalize
255 * the path. This works in place and won't rollback any
256 * changes on failure. */
259 _cleanup_free_
char *orig
= NULL
;
262 if (!path_is_absolute(*s
)) {
269 t
= prefix_root(root
, orig
);
277 r
= chase_symlinks(t
, root
, 0, &u
);
295 x
= path_startswith(u
, root
);
297 /* restore the slash if it was lost */
298 if (!startswith(x
, "/"))
309 /* canonicalized path goes outside of
310 * prefix, keep the original path instead */
311 free_and_replace(u
, orig
);
327 char **path_strv_resolve_uniq(char **l
, const char *root
) {
332 if (!path_strv_resolve(l
, root
))
338 char *path_kill_slashes(char *path
) {
342 /* Removes redundant inner and trailing slashes. Modifies the
343 * passed string in-place.
345 * ///foo///bar/ becomes /foo/bar
348 for (f
= path
, t
= path
; *f
; f
++) {
363 /* Special rule, if we are talking of the root directory, a
364 trailing slash is good */
366 if (t
== path
&& slash
)
373 char* path_startswith(const char *path
, const char *prefix
) {
377 /* Returns a pointer to the start of the first component after the parts matched by
379 * - both paths are absolute or both paths are relative,
381 * - each component in prefix in turn matches a component in path at the same position.
382 * An empty string will be returned when the prefix and path are equivalent.
384 * Returns NULL otherwise.
387 if ((path
[0] == '/') != (prefix
[0] == '/'))
393 path
+= strspn(path
, "/");
394 prefix
+= strspn(prefix
, "/");
402 a
= strcspn(path
, "/");
403 b
= strcspn(prefix
, "/");
408 if (memcmp(path
, prefix
, a
) != 0)
416 int path_compare(const char *a
, const char *b
) {
422 /* A relative path and an abolute path must not compare as equal.
423 * Which one is sorted before the other does not really matter.
424 * Here a relative path is ordered before an absolute path. */
425 d
= (a
[0] == '/') - (b
[0] == '/');
435 if (*a
== 0 && *b
== 0)
438 /* Order prefixes first: "/foo" before "/foo/bar" */
447 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
448 d
= memcmp(a
, b
, MIN(j
, k
));
450 return (d
> 0) - (d
< 0); /* sign of d */
452 /* Sort "/foo/a" before "/foo/aaa" */
453 d
= (j
> k
) - (j
< k
); /* sign of (j - k) */
462 bool path_equal(const char *a
, const char *b
) {
463 return path_compare(a
, b
) == 0;
466 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
467 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
470 char* path_join(const char *root
, const char *path
, const char *rest
) {
474 return strjoin(root
, endswith(root
, "/") ? "" : "/",
475 path
[0] == '/' ? path
+1 : path
,
476 rest
? (endswith(path
, "/") ? "" : "/") : NULL
,
477 rest
&& rest
[0] == '/' ? rest
+1 : rest
);
480 rest
? (endswith(path
, "/") ? "" : "/") : NULL
,
481 rest
&& rest
[0] == '/' ? rest
+1 : rest
);
484 int find_binary(const char *name
, char **ret
) {
491 if (access(name
, X_OK
) < 0)
495 r
= path_make_absolute_cwd(name
, ret
);
504 * Plain getenv, not secure_getenv, because we want
505 * to actually allow the user to pick the binary.
511 last_error
= -ENOENT
;
514 _cleanup_free_
char *j
= NULL
, *element
= NULL
;
516 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
522 if (!path_is_absolute(element
))
525 j
= strjoin(element
, "/", name
);
529 if (access(j
, X_OK
) >= 0) {
533 *ret
= path_kill_slashes(j
);
546 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
547 bool changed
= false;
548 const char* const* i
;
555 STRV_FOREACH(i
, paths
) {
559 if (stat(*i
, &stats
) < 0)
562 u
= timespec_load(&stats
.st_mtim
);
568 log_debug("timestamp of '%s' changed", *i
);
570 /* update timestamp */
581 static int binary_is_good(const char *binary
) {
582 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
585 r
= find_binary(binary
, &p
);
591 /* An fsck that is linked to /bin/true is a non-existent
594 r
= readlink_malloc(p
, &d
);
595 if (r
== -EINVAL
) /* not a symlink */
600 return !PATH_IN_SET(d
, "true"
606 int fsck_exists(const char *fstype
) {
611 if (streq(fstype
, "auto"))
614 checker
= strjoina("fsck.", fstype
);
615 return binary_is_good(checker
);
618 int mkfs_exists(const char *fstype
) {
623 if (streq(fstype
, "auto"))
626 mkfs
= strjoina("mkfs.", fstype
);
627 return binary_is_good(mkfs
);
630 char *prefix_root(const char *root
, const char *path
) {
634 /* If root is passed, prefixes path with it. Otherwise returns
639 /* First, drop duplicate prefixing slashes from the path */
640 while (path
[0] == '/' && path
[1] == '/')
643 if (isempty(root
) || path_equal(root
, "/"))
646 l
= strlen(root
) + 1 + strlen(path
) + 1;
654 while (p
> n
&& p
[-1] == '/')
664 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
669 * This function is intended to be used in command line
670 * parsers, to handle paths that are passed in. It makes the
671 * path absolute, and reduces it to NULL if omitted or
672 * root (the latter optionally).
674 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
675 * SUCCESS! Hence, do not pass in uninitialized pointers.
683 r
= path_make_absolute_cwd(path
, &p
);
685 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
687 path_kill_slashes(p
);
688 if (suppress_root
&& path_equal(p
, "/"))
696 char* dirname_malloc(const char *path
) {
697 char *d
, *dir
, *dir2
;
717 const char *last_path_component(const char *path
) {
718 /* Finds the last component of the path, preserving the
719 * optional trailing slash that signifies a directory.
726 * This is different than basename, which returns "" when
727 * a trailing slash is present.
732 l
= k
= strlen(path
);
733 if (l
== 0) /* special case — an empty string */
736 while (k
> 0 && path
[k
-1] == '/')
739 if (k
== 0) /* the root directory */
742 while (k
> 0 && path
[k
-1] != '/')
748 bool filename_is_valid(const char *p
) {
754 if (dot_or_dot_dot(p
))
757 e
= strchrnul(p
, '/');
761 if (e
- p
> FILENAME_MAX
)
767 bool path_is_normalized(const char *p
) {
772 if (dot_or_dot_dot(p
))
775 if (startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
778 if (strlen(p
)+1 > PATH_MAX
)
781 if (startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
790 char *file_in_same_dir(const char *path
, const char *filename
) {
797 /* This removes the last component of path and appends
798 * filename, unless the latter is absolute anyway or the
801 if (path_is_absolute(filename
))
802 return strdup(filename
);
804 e
= strrchr(path
, '/');
806 return strdup(filename
);
808 k
= strlen(filename
);
809 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
813 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
817 bool hidden_or_backup_file(const char *filename
) {
822 if (filename
[0] == '.' ||
823 streq(filename
, "lost+found") ||
824 streq(filename
, "aquota.user") ||
825 streq(filename
, "aquota.group") ||
826 endswith(filename
, "~"))
829 p
= strrchr(filename
, '.');
833 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
834 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
835 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
836 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
837 * string. Specifically: there's now:
839 * The generic suffixes "~" and ".bak" for backup files
840 * The generic prefix "." for hidden files
842 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
843 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
846 return STR_IN_SET(p
+ 1,
866 bool is_device_path(const char *path
) {
868 /* Returns true on paths that refer to a device, either in
869 * sysfs or in /dev */
871 return path_startswith(path
, "/dev/") ||
872 path_startswith(path
, "/sys/");
875 bool is_deviceallow_pattern(const char *path
) {
876 return path_startswith(path
, "/dev/") ||
877 startswith(path
, "block-") ||
878 startswith(path
, "char-");
881 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
885 /* Try to guess if systemd installation is later than the specified version. This
886 * is hacky and likely to yield false negatives, particularly if the installation
887 * is non-standard. False positives should be relatively rare.
890 NULSTR_FOREACH(pattern
,
891 /* /lib works for systems without usr-merge, and for systems with a sane
892 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
893 * for Gentoo which does a merge without making /lib a symlink.
895 "lib/systemd/libsystemd-shared-*.so\0"
896 "lib64/systemd/libsystemd-shared-*.so\0"
897 "usr/lib/systemd/libsystemd-shared-*.so\0"
898 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
900 _cleanup_strv_free_
char **names
= NULL
;
901 _cleanup_free_
char *path
= NULL
;
904 path
= prefix_root(root
, pattern
);
908 r
= glob_extend(&names
, path
);
914 assert_se((c
= endswith(path
, "*.so")));
915 *c
= '\0'; /* truncate the glob part */
917 STRV_FOREACH(name
, names
) {
918 /* This is most likely to run only once, hence let's not optimize anything. */
922 t
= startswith(*name
, path
);
926 t2
= endswith(t
, ".so");
930 t2
[0] = '\0'; /* truncate the suffix */
932 r
= safe_atou(t
, &version
);
934 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
938 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
940 version
>= minimal_version
? "OK" : "too old");
941 if (version
>= minimal_version
)
949 bool dot_or_dot_dot(const char *path
) {