2 This file is part of systemd.
4 Copyright 2010-2012 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
28 /* When we include libgen.h because we need dirname() we immediately
29 * undefine basename() since libgen.h defines it as a macro to the
30 * POSIX version which is really broken. We prefer GNU basename(). */
34 #include "alloc-util.h"
35 #include "extract-word.h"
37 #include "glob-util.h"
41 #include "parse-util.h"
42 #include "path-util.h"
43 #include "stat-util.h"
44 #include "string-util.h"
46 #include "time-util.h"
48 bool path_is_absolute(const char *p
) {
52 bool is_path(const char *p
) {
53 return !!strchr(p
, '/');
56 int path_split_and_make_absolute(const char *p
, char ***ret
) {
63 l
= strv_split(p
, ":");
67 r
= path_strv_make_absolute_cwd(l
);
77 char *path_make_absolute(const char *p
, const char *prefix
) {
80 /* Makes every item in the list an absolute path by prepending
81 * the prefix, if specified and necessary */
83 if (path_is_absolute(p
) || !prefix
)
86 return strjoin(prefix
, "/", p
);
89 int path_make_absolute_cwd(const char *p
, char **ret
) {
95 /* Similar to path_make_absolute(), but prefixes with the
96 * current working directory. */
98 if (path_is_absolute(p
))
101 _cleanup_free_
char *cwd
= NULL
;
103 cwd
= get_current_dir_name();
105 return negative_errno();
107 c
= strjoin(cwd
, "/", p
);
116 int path_make_relative(const char *from_dir
, const char *to_path
, char **_r
) {
124 /* Strips the common part, and adds ".." elements as necessary. */
126 if (!path_is_absolute(from_dir
))
129 if (!path_is_absolute(to_path
))
132 /* Skip the common part. */
136 from_dir
+= strspn(from_dir
, "/");
137 to_path
+= strspn(to_path
, "/");
141 /* from_dir equals to_path. */
144 /* from_dir is a parent directory of to_path. */
149 path_kill_slashes(r
);
158 a
= strcspn(from_dir
, "/");
159 b
= strcspn(to_path
, "/");
164 if (memcmp(from_dir
, to_path
, a
) != 0)
171 /* If we're here, then "from_dir" has one or more elements that need to
172 * be replaced with "..". */
174 /* Count the number of necessary ".." elements. */
175 for (n_parents
= 0;;) {
178 from_dir
+= strspn(from_dir
, "/");
183 w
= strcspn(from_dir
, "/");
185 /* If this includes ".." we can't do a simple series of "..", refuse */
186 if (w
== 2 && from_dir
[0] == '.' && from_dir
[1] == '.')
189 /* Count number of elements, except if they are "." */
190 if (w
!= 1 || from_dir
[0] != '.')
196 r
= new(char, n_parents
* 3 + strlen(to_path
) + 1);
200 for (p
= r
; n_parents
> 0; n_parents
--)
201 p
= mempcpy(p
, "../", 3);
204 path_kill_slashes(r
);
210 int path_strv_make_absolute_cwd(char **l
) {
214 /* Goes through every item in the string list and makes it
215 * absolute. This works in place and won't rollback any
216 * changes on failure. */
221 r
= path_make_absolute_cwd(*s
, &t
);
232 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
= prefix_root(root
, orig
);
264 r
= chase_symlinks(t
, root
, 0, &u
);
283 x
= path_startswith(u
, root
);
285 /* restore the slash if it was lost */
286 if (!startswith(x
, "/"))
297 /* canonicalized path goes outside of
298 * prefix, keep the original path instead */
299 free_and_replace(u
, orig
);
315 char **path_strv_resolve_uniq(char **l
, const char *root
) {
320 if (!path_strv_resolve(l
, root
))
326 char *path_kill_slashes(char *path
) {
330 /* Removes redundant inner and trailing slashes. Modifies the
331 * passed string in-place.
333 * ///foo///bar/ becomes /foo/bar
336 for (f
= path
, t
= path
; *f
; f
++) {
351 /* Special rule, if we are talking of the root directory, a
352 trailing slash is good */
354 if (t
== path
&& slash
)
361 char* path_startswith(const char *path
, const char *prefix
) {
365 /* Returns a pointer to the start of the first component after the parts matched by
367 * - both paths are absolute or both paths are relative,
369 * - each component in prefix in turn matches a component in path at the same position.
370 * An empty string will be returned when the prefix and path are equivalent.
372 * Returns NULL otherwise.
375 if ((path
[0] == '/') != (prefix
[0] == '/'))
381 path
+= strspn(path
, "/");
382 prefix
+= strspn(prefix
, "/");
390 a
= strcspn(path
, "/");
391 b
= strcspn(prefix
, "/");
396 if (memcmp(path
, prefix
, a
) != 0)
404 int path_compare(const char *a
, const char *b
) {
410 /* A relative path and an abolute path must not compare as equal.
411 * Which one is sorted before the other does not really matter.
412 * Here a relative path is ordered before an absolute path. */
413 d
= (a
[0] == '/') - (b
[0] == '/');
423 if (*a
== 0 && *b
== 0)
426 /* Order prefixes first: "/foo" before "/foo/bar" */
435 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
436 d
= memcmp(a
, b
, MIN(j
, k
));
438 return (d
> 0) - (d
< 0); /* sign of d */
440 /* Sort "/foo/a" before "/foo/aaa" */
441 d
= (j
> k
) - (j
< k
); /* sign of (j - k) */
450 bool path_equal(const char *a
, const char *b
) {
451 return path_compare(a
, b
) == 0;
454 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
455 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
458 char* path_join(const char *root
, const char *path
, const char *rest
) {
462 return strjoin(root
, endswith(root
, "/") ? "" : "/",
463 path
[0] == '/' ? path
+1 : path
,
464 rest
? (endswith(path
, "/") ? "" : "/") : NULL
,
465 rest
&& rest
[0] == '/' ? rest
+1 : rest
);
468 rest
? (endswith(path
, "/") ? "" : "/") : NULL
,
469 rest
&& rest
[0] == '/' ? rest
+1 : rest
);
472 int find_binary(const char *name
, char **ret
) {
479 if (access(name
, X_OK
) < 0)
483 r
= path_make_absolute_cwd(name
, ret
);
492 * Plain getenv, not secure_getenv, because we want
493 * to actually allow the user to pick the binary.
499 last_error
= -ENOENT
;
502 _cleanup_free_
char *j
= NULL
, *element
= NULL
;
504 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
510 if (!path_is_absolute(element
))
513 j
= strjoin(element
, "/", name
);
517 if (access(j
, X_OK
) >= 0) {
521 *ret
= path_kill_slashes(j
);
534 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
535 bool changed
= false;
536 const char* const* i
;
543 STRV_FOREACH(i
, paths
) {
547 if (stat(*i
, &stats
) < 0)
550 u
= timespec_load(&stats
.st_mtim
);
556 log_debug("timestamp of '%s' changed", *i
);
558 /* update timestamp */
569 static int binary_is_good(const char *binary
) {
570 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
573 r
= find_binary(binary
, &p
);
579 /* An fsck that is linked to /bin/true is a non-existent
582 r
= readlink_malloc(p
, &d
);
583 if (r
== -EINVAL
) /* not a symlink */
588 return !PATH_IN_SET(d
, "true"
594 int fsck_exists(const char *fstype
) {
599 if (streq(fstype
, "auto"))
602 checker
= strjoina("fsck.", fstype
);
603 return binary_is_good(checker
);
606 int mkfs_exists(const char *fstype
) {
611 if (streq(fstype
, "auto"))
614 mkfs
= strjoina("mkfs.", fstype
);
615 return binary_is_good(mkfs
);
618 char *prefix_root(const char *root
, const char *path
) {
622 /* If root is passed, prefixes path with it. Otherwise returns
627 /* First, drop duplicate prefixing slashes from the path */
628 while (path
[0] == '/' && path
[1] == '/')
631 if (isempty(root
) || path_equal(root
, "/"))
634 l
= strlen(root
) + 1 + strlen(path
) + 1;
642 while (p
> n
&& p
[-1] == '/')
652 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
657 * This function is intended to be used in command line
658 * parsers, to handle paths that are passed in. It makes the
659 * path absolute, and reduces it to NULL if omitted or
660 * root (the latter optionally).
662 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
663 * SUCCESS! Hence, do not pass in uninitialized pointers.
671 r
= path_make_absolute_cwd(path
, &p
);
673 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
675 path_kill_slashes(p
);
676 if (suppress_root
&& path_equal(p
, "/"))
684 char* dirname_malloc(const char *path
) {
685 char *d
, *dir
, *dir2
;
705 bool filename_is_valid(const char *p
) {
711 if (dot_or_dot_dot(p
))
714 e
= strchrnul(p
, '/');
718 if (e
- p
> FILENAME_MAX
)
724 bool path_is_normalized(const char *p
) {
729 if (dot_or_dot_dot(p
))
732 if (startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
735 if (strlen(p
)+1 > PATH_MAX
)
738 if (startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
747 char *file_in_same_dir(const char *path
, const char *filename
) {
754 /* This removes the last component of path and appends
755 * filename, unless the latter is absolute anyway or the
758 if (path_is_absolute(filename
))
759 return strdup(filename
);
761 e
= strrchr(path
, '/');
763 return strdup(filename
);
765 k
= strlen(filename
);
766 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
770 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
774 bool hidden_or_backup_file(const char *filename
) {
779 if (filename
[0] == '.' ||
780 streq(filename
, "lost+found") ||
781 streq(filename
, "aquota.user") ||
782 streq(filename
, "aquota.group") ||
783 endswith(filename
, "~"))
786 p
= strrchr(filename
, '.');
790 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
791 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
792 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
793 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
794 * string. Specifically: there's now:
796 * The generic suffixes "~" and ".bak" for backup files
797 * The generic prefix "." for hidden files
799 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
800 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
803 return STR_IN_SET(p
+ 1,
823 bool is_device_path(const char *path
) {
825 /* Returns true on paths that refer to a device, either in
826 * sysfs or in /dev */
828 return path_startswith(path
, "/dev/") ||
829 path_startswith(path
, "/sys/");
832 bool is_deviceallow_pattern(const char *path
) {
833 return path_startswith(path
, "/dev/") ||
834 startswith(path
, "block-") ||
835 startswith(path
, "char-");
838 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
842 /* Try to guess if systemd installation is later than the specified version. This
843 * is hacky and likely to yield false negatives, particularly if the installation
844 * is non-standard. False positives should be relatively rare.
847 NULSTR_FOREACH(pattern
,
848 /* /lib works for systems without usr-merge, and for systems with a sane
849 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
850 * for Gentoo which does a merge without making /lib a symlink.
852 "lib/systemd/libsystemd-shared-*.so\0"
853 "usr/lib/systemd/libsystemd-shared-*.so\0") {
855 _cleanup_strv_free_
char **names
= NULL
;
856 _cleanup_free_
char *path
= NULL
;
859 path
= prefix_root(root
, pattern
);
863 r
= glob_extend(&names
, path
);
869 assert_se((c
= endswith(path
, "*.so")));
870 *c
= '\0'; /* truncate the glob part */
872 STRV_FOREACH(name
, names
) {
873 /* This is most likely to run only once, hence let's not optimize anything. */
877 t
= startswith(*name
, path
);
881 t2
= endswith(t
, ".so");
885 t2
[0] = '\0'; /* truncate the suffix */
887 r
= safe_atou(t
, &version
);
889 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
893 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
895 version
>= minimal_version
? "OK" : "too old");
896 if (version
>= minimal_version
)
904 bool dot_or_dot_dot(const char *path
) {