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. */
137 from_dir
+= strspn(from_dir
, "/");
138 to_path
+= strspn(to_path
, "/");
142 /* from_dir equals to_path. */
145 /* from_dir is a parent directory of to_path. */
151 path_kill_slashes(r
);
160 a
= strcspn(from_dir
, "/");
161 b
= strcspn(to_path
, "/");
166 if (memcmp(from_dir
, to_path
, a
) != 0)
173 /* If we're here, then "from_dir" has one or more elements that need to
174 * be replaced with "..". */
176 /* Count the number of necessary ".." elements. */
177 for (n_parents
= 0;;) {
178 from_dir
+= strspn(from_dir
, "/");
183 from_dir
+= strcspn(from_dir
, "/");
187 r
= malloc(n_parents
* 3 + strlen(to_path
) + 1);
191 for (p
= r
; n_parents
> 0; n_parents
--, p
+= 3)
195 path_kill_slashes(r
);
201 int path_strv_make_absolute_cwd(char **l
) {
205 /* Goes through every item in the string list and makes it
206 * absolute. This works in place and won't rollback any
207 * changes on failure. */
212 r
= path_make_absolute_cwd(*s
, &t
);
223 char **path_strv_resolve(char **l
, const char *root
) {
232 /* Goes through every item in the string list and canonicalize
233 * the path. This works in place and won't rollback any
234 * changes on failure. */
237 _cleanup_free_
char *orig
= NULL
;
240 if (!path_is_absolute(*s
)) {
247 t
= prefix_root(root
, orig
);
255 r
= chase_symlinks(t
, root
, &u
);
274 x
= path_startswith(u
, root
);
276 /* restore the slash if it was lost */
277 if (!startswith(x
, "/"))
288 /* canonicalized path goes outside of
289 * prefix, keep the original path instead */
290 free_and_replace(u
, orig
);
306 char **path_strv_resolve_uniq(char **l
, const char *root
) {
311 if (!path_strv_resolve(l
, root
))
317 char *path_kill_slashes(char *path
) {
321 /* Removes redundant inner and trailing slashes. Modifies the
322 * passed string in-place.
324 * ///foo///bar/ becomes /foo/bar
327 for (f
= path
, t
= path
; *f
; f
++) {
342 /* Special rule, if we are talking of the root directory, a
343 trailing slash is good */
345 if (t
== path
&& slash
)
352 char* path_startswith(const char *path
, const char *prefix
) {
356 /* Returns a pointer to the start of the first component after the parts matched by
358 * - both paths are absolute or both paths are relative,
360 * - each component in prefix in turn matches a component in path at the same position.
361 * An empty string will be returned when the prefix and path are equivalent.
363 * Returns NULL otherwise.
366 if ((path
[0] == '/') != (prefix
[0] == '/'))
372 path
+= strspn(path
, "/");
373 prefix
+= strspn(prefix
, "/");
381 a
= strcspn(path
, "/");
382 b
= strcspn(prefix
, "/");
387 if (memcmp(path
, prefix
, a
) != 0)
395 int path_compare(const char *a
, const char *b
) {
401 /* A relative path and an abolute path must not compare as equal.
402 * Which one is sorted before the other does not really matter.
403 * Here a relative path is ordered before an absolute path. */
404 d
= (a
[0] == '/') - (b
[0] == '/');
414 if (*a
== 0 && *b
== 0)
417 /* Order prefixes first: "/foo" before "/foo/bar" */
426 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
427 d
= memcmp(a
, b
, MIN(j
, k
));
429 return (d
> 0) - (d
< 0); /* sign of d */
431 /* Sort "/foo/a" before "/foo/aaa" */
432 d
= (j
> k
) - (j
< k
); /* sign of (j - k) */
441 bool path_equal(const char *a
, const char *b
) {
442 return path_compare(a
, b
) == 0;
445 bool path_equal_or_files_same(const char *a
, const char *b
) {
446 return path_equal(a
, b
) || files_same(a
, b
) > 0;
449 char* path_join(const char *root
, const char *path
, const char *rest
) {
453 return strjoin(root
, endswith(root
, "/") ? "" : "/",
454 path
[0] == '/' ? path
+1 : path
,
455 rest
? (endswith(path
, "/") ? "" : "/") : NULL
,
456 rest
&& rest
[0] == '/' ? rest
+1 : rest
);
459 rest
? (endswith(path
, "/") ? "" : "/") : NULL
,
460 rest
&& rest
[0] == '/' ? rest
+1 : rest
);
463 int find_binary(const char *name
, char **ret
) {
470 if (access(name
, X_OK
) < 0)
474 r
= path_make_absolute_cwd(name
, ret
);
483 * Plain getenv, not secure_getenv, because we want
484 * to actually allow the user to pick the binary.
490 last_error
= -ENOENT
;
493 _cleanup_free_
char *j
= NULL
, *element
= NULL
;
495 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
501 if (!path_is_absolute(element
))
504 j
= strjoin(element
, "/", name
);
508 if (access(j
, X_OK
) >= 0) {
512 *ret
= path_kill_slashes(j
);
525 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
526 bool changed
= false;
527 const char* const* i
;
534 STRV_FOREACH(i
, paths
) {
538 if (stat(*i
, &stats
) < 0)
541 u
= timespec_load(&stats
.st_mtim
);
547 log_debug("timestamp of '%s' changed", *i
);
549 /* update timestamp */
560 static int binary_is_good(const char *binary
) {
561 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
564 r
= find_binary(binary
, &p
);
570 /* An fsck that is linked to /bin/true is a non-existent
573 r
= readlink_malloc(p
, &d
);
574 if (r
== -EINVAL
) /* not a symlink */
579 return !PATH_IN_SET(d
, "true"
585 int fsck_exists(const char *fstype
) {
590 if (streq(fstype
, "auto"))
593 checker
= strjoina("fsck.", fstype
);
594 return binary_is_good(checker
);
597 int mkfs_exists(const char *fstype
) {
602 if (streq(fstype
, "auto"))
605 mkfs
= strjoina("mkfs.", fstype
);
606 return binary_is_good(mkfs
);
609 char *prefix_root(const char *root
, const char *path
) {
613 /* If root is passed, prefixes path with it. Otherwise returns
618 /* First, drop duplicate prefixing slashes from the path */
619 while (path
[0] == '/' && path
[1] == '/')
622 if (isempty(root
) || path_equal(root
, "/"))
625 l
= strlen(root
) + 1 + strlen(path
) + 1;
633 while (p
> n
&& p
[-1] == '/')
643 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
648 * This function is intended to be used in command line
649 * parsers, to handle paths that are passed in. It makes the
650 * path absolute, and reduces it to NULL if omitted or
651 * root (the latter optionally).
653 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
654 * SUCCESS! Hence, do not pass in uninitialized pointers.
662 r
= path_make_absolute_cwd(path
, &p
);
664 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
666 path_kill_slashes(p
);
667 if (suppress_root
&& path_equal(p
, "/"))
675 char* dirname_malloc(const char *path
) {
676 char *d
, *dir
, *dir2
;
696 bool filename_is_valid(const char *p
) {
708 e
= strchrnul(p
, '/');
712 if (e
- p
> FILENAME_MAX
)
718 bool path_is_safe(const char *p
) {
723 if (streq(p
, "..") || startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
726 if (strlen(p
)+1 > PATH_MAX
)
729 /* The following two checks are not really dangerous, but hey, they still are confusing */
730 if (streq(p
, ".") || startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
739 char *file_in_same_dir(const char *path
, const char *filename
) {
746 /* This removes the last component of path and appends
747 * filename, unless the latter is absolute anyway or the
750 if (path_is_absolute(filename
))
751 return strdup(filename
);
753 e
= strrchr(path
, '/');
755 return strdup(filename
);
757 k
= strlen(filename
);
758 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
762 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
766 bool hidden_or_backup_file(const char *filename
) {
771 if (filename
[0] == '.' ||
772 streq(filename
, "lost+found") ||
773 streq(filename
, "aquota.user") ||
774 streq(filename
, "aquota.group") ||
775 endswith(filename
, "~"))
778 p
= strrchr(filename
, '.');
782 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
783 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
784 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
785 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
786 * string. Specifically: there's now:
788 * The generic suffixes "~" and ".bak" for backup files
789 * The generic prefix "." for hidden files
791 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
792 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
795 return STR_IN_SET(p
+ 1,
815 bool is_device_path(const char *path
) {
817 /* Returns true on paths that refer to a device, either in
818 * sysfs or in /dev */
820 return path_startswith(path
, "/dev/") ||
821 path_startswith(path
, "/sys/");
824 bool is_deviceallow_pattern(const char *path
) {
825 return path_startswith(path
, "/dev/") ||
826 startswith(path
, "block-") ||
827 startswith(path
, "char-");
830 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
834 /* Try to guess if systemd installation is later than the specified version. This
835 * is hacky and likely to yield false negatives, particularly if the installation
836 * is non-standard. False positives should be relatively rare.
839 NULSTR_FOREACH(pattern
,
840 /* /lib works for systems without usr-merge, and for systems with a sane
841 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
842 * for Gentoo which does a merge without making /lib a symlink.
844 "lib/systemd/libsystemd-shared-*.so\0"
845 "usr/lib/systemd/libsystemd-shared-*.so\0") {
847 _cleanup_strv_free_
char **names
= NULL
;
848 _cleanup_free_
char *path
= NULL
;
851 path
= prefix_root(root
, pattern
);
855 r
= glob_extend(&names
, path
);
861 assert_se((c
= endswith(path
, "*.so")));
862 *c
= '\0'; /* truncate the glob part */
864 STRV_FOREACH(name
, names
) {
865 /* This is most likely to run only once, hence let's not optimize anything. */
869 t
= startswith(*name
, path
);
873 t2
= endswith(t
, ".so");
877 t2
[0] = '\0'; /* truncate the suffix */
879 r
= safe_atou(t
, &version
);
881 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
885 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
887 version
>= minimal_version
? "OK" : "too old");
888 if (version
>= minimal_version
)