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"
40 #include "path-util.h"
41 #include "stat-util.h"
42 #include "string-util.h"
44 #include "time-util.h"
46 bool path_is_absolute(const char *p) {
50 bool is_path(const char *p) {
51 return !!strchr(p, '/');
54 #if 0 /// UNNEEDED by elogind
55 int path_split_and_make_absolute(const char *p, char ***ret) {
62 l = strv_split(p, ":");
66 r = path_strv_make_absolute_cwd(l);
76 char *path_make_absolute(const char *p, const char *prefix) {
79 /* Makes every item in the list an absolute path by prepending
80 * the prefix, if specified and necessary */
82 if (path_is_absolute(p) || !prefix)
85 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 #if 0 /// UNNEEDED by elogind
117 int path_make_relative(const char *from_dir, const char *to_path, char **_r) {
125 /* Strips the common part, and adds ".." elements as necessary. */
127 if (!path_is_absolute(from_dir))
130 if (!path_is_absolute(to_path))
133 /* Skip the common part. */
138 from_dir += strspn(from_dir, "/");
139 to_path += strspn(to_path, "/");
143 /* from_dir equals to_path. */
146 /* from_dir is a parent directory of to_path. */
152 path_kill_slashes(r);
161 a = strcspn(from_dir, "/");
162 b = strcspn(to_path, "/");
167 if (memcmp(from_dir, to_path, a) != 0)
174 /* If we're here, then "from_dir" has one or more elements that need to
175 * be replaced with "..". */
177 /* Count the number of necessary ".." elements. */
178 for (n_parents = 0;;) {
179 from_dir += strspn(from_dir, "/");
184 from_dir += strcspn(from_dir, "/");
188 r = malloc(n_parents * 3 + strlen(to_path) + 1);
192 for (p = r; n_parents > 0; n_parents--, p += 3)
196 path_kill_slashes(r);
202 int path_strv_make_absolute_cwd(char **l) {
206 /* Goes through every item in the string list and makes it
207 * absolute. This works in place and won't rollback any
208 * changes on failure. */
213 r = path_make_absolute_cwd(*s, &t);
225 char **path_strv_resolve(char **l, const char *root) {
234 /* Goes through every item in the string list and canonicalize
235 * the path. This works in place and won't rollback any
236 * changes on failure. */
239 _cleanup_free_ char *orig = NULL;
242 if (!path_is_absolute(*s)) {
249 t = prefix_root(root, orig);
257 r = chase_symlinks(t, root, 0, &u);
276 x = path_startswith(u, root);
278 /* restore the slash if it was lost */
279 if (!startswith(x, "/"))
290 /* canonicalized path goes outside of
291 * prefix, keep the original path instead */
292 free_and_replace(u, orig);
308 char **path_strv_resolve_uniq(char **l, const char *root) {
313 if (!path_strv_resolve(l, root))
319 char *path_kill_slashes(char *path) {
323 /* Removes redundant inner and trailing slashes. Modifies the
324 * passed string in-place.
326 * ///foo///bar/ becomes /foo/bar
329 for (f = path, t = path; *f; f++) {
344 /* Special rule, if we are talking of the root directory, a
345 trailing slash is good */
347 if (t == path && slash)
354 char* path_startswith(const char *path, const char *prefix) {
358 /* Returns a pointer to the start of the first component after the parts matched by
360 * - both paths are absolute or both paths are relative,
362 * - each component in prefix in turn matches a component in path at the same position.
363 * An empty string will be returned when the prefix and path are equivalent.
365 * Returns NULL otherwise.
368 if ((path[0] == '/') != (prefix[0] == '/'))
374 path += strspn(path, "/");
375 prefix += strspn(prefix, "/");
383 a = strcspn(path, "/");
384 b = strcspn(prefix, "/");
389 if (memcmp(path, prefix, a) != 0)
397 int path_compare(const char *a, const char *b) {
403 /* A relative path and an abolute path must not compare as equal.
404 * Which one is sorted before the other does not really matter.
405 * Here a relative path is ordered before an absolute path. */
406 d = (a[0] == '/') - (b[0] == '/');
416 if (*a == 0 && *b == 0)
419 /* Order prefixes first: "/foo" before "/foo/bar" */
428 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
429 d = memcmp(a, b, MIN(j, k));
431 return (d > 0) - (d < 0); /* sign of d */
433 /* Sort "/foo/a" before "/foo/aaa" */
434 d = (j > k) - (j < k); /* sign of (j - k) */
443 bool path_equal(const char *a, const char *b) {
444 return path_compare(a, b) == 0;
447 bool path_equal_or_files_same(const char *a, const char *b) {
448 return path_equal(a, b) || files_same(a, b) > 0;
451 #if 0 /// UNNEEDED by elogind
452 char* path_join(const char *root, const char *path, const char *rest) {
456 return strjoin(root, endswith(root, "/") ? "" : "/",
457 path[0] == '/' ? path+1 : path,
458 rest ? (endswith(path, "/") ? "" : "/") : NULL,
459 rest && rest[0] == '/' ? rest+1 : rest);
462 rest ? (endswith(path, "/") ? "" : "/") : NULL,
463 rest && rest[0] == '/' ? rest+1 : rest);
466 int find_binary(const char *name, char **ret) {
473 if (access(name, X_OK) < 0)
477 r = path_make_absolute_cwd(name, ret);
486 * Plain getenv, not secure_getenv, because we want
487 * to actually allow the user to pick the binary.
493 last_error = -ENOENT;
496 _cleanup_free_ char *j = NULL, *element = NULL;
498 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
504 if (!path_is_absolute(element))
507 j = strjoin(element, "/", name);
511 if (access(j, X_OK) >= 0) {
515 *ret = path_kill_slashes(j);
528 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
529 bool changed = false;
530 const char* const* i;
537 STRV_FOREACH(i, paths) {
541 if (stat(*i, &stats) < 0)
544 u = timespec_load(&stats.st_mtim);
550 log_debug("timestamp of '%s' changed", *i);
552 /* update timestamp */
563 static int binary_is_good(const char *binary) {
564 _cleanup_free_ char *p = NULL, *d = NULL;
567 r = find_binary(binary, &p);
573 /* An fsck that is linked to /bin/true is a non-existent
576 r = readlink_malloc(p, &d);
577 if (r == -EINVAL) /* not a symlink */
582 return !PATH_IN_SET(d, "true"
588 int fsck_exists(const char *fstype) {
593 if (streq(fstype, "auto"))
596 checker = strjoina("fsck.", fstype);
597 return binary_is_good(checker);
600 int mkfs_exists(const char *fstype) {
605 if (streq(fstype, "auto"))
608 mkfs = strjoina("mkfs.", fstype);
609 return binary_is_good(mkfs);
613 char *prefix_root(const char *root, const char *path) {
617 /* If root is passed, prefixes path with it. Otherwise returns
622 /* First, drop duplicate prefixing slashes from the path */
623 while (path[0] == '/' && path[1] == '/')
626 if (isempty(root) || path_equal(root, "/"))
629 l = strlen(root) + 1 + strlen(path) + 1;
637 while (p > n && p[-1] == '/')
647 #if 0 /// UNNEEDED by elogind
648 int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
653 * This function is intended to be used in command line
654 * parsers, to handle paths that are passed in. It makes the
655 * path absolute, and reduces it to NULL if omitted or
656 * root (the latter optionally).
658 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
659 * SUCCESS! Hence, do not pass in uninitialized pointers.
667 r = path_make_absolute_cwd(path, &p);
669 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
671 path_kill_slashes(p);
672 if (suppress_root && path_equal(p, "/"))
681 char* dirname_malloc(const char *path) {
682 char *d, *dir, *dir2;
702 bool filename_is_valid(const char *p) {
708 if (dot_or_dot_dot(p))
711 e = strchrnul(p, '/');
715 if (e - p > FILENAME_MAX)
721 bool path_is_safe(const char *p) {
726 if (dot_or_dot_dot(p))
729 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
732 if (strlen(p)+1 > PATH_MAX)
735 /* The following two checks are not really dangerous, but hey, they still are confusing */
736 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
745 char *file_in_same_dir(const char *path, const char *filename) {
752 /* This removes the last component of path and appends
753 * filename, unless the latter is absolute anyway or the
756 if (path_is_absolute(filename))
757 return strdup(filename);
759 e = strrchr(path, '/');
761 return strdup(filename);
763 k = strlen(filename);
764 ret = new(char, (e + 1 - path) + k + 1);
768 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
772 bool hidden_or_backup_file(const char *filename) {
777 if (filename[0] == '.' ||
778 streq(filename, "lost+found") ||
779 streq(filename, "aquota.user") ||
780 streq(filename, "aquota.group") ||
781 endswith(filename, "~"))
784 p = strrchr(filename, '.');
788 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
789 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
790 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
791 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
792 * string. Specifically: there's now:
794 * The generic suffixes "~" and ".bak" for backup files
795 * The generic prefix "." for hidden files
797 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
798 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
801 return STR_IN_SET(p + 1,
821 #if 0 /// UNNEEDED by elogind
822 bool is_device_path(const char *path) {
824 /* Returns true on paths that refer to a device, either in
825 * sysfs or in /dev */
827 return path_startswith(path, "/dev/") ||
828 path_startswith(path, "/sys/");
831 bool is_deviceallow_pattern(const char *path) {
832 return path_startswith(path, "/dev/") ||
833 startswith(path, "block-") ||
834 startswith(path, "char-");
837 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
841 /* Try to guess if systemd installation is later than the specified version. This
842 * is hacky and likely to yield false negatives, particularly if the installation
843 * is non-standard. False positives should be relatively rare.
846 NULSTR_FOREACH(pattern,
847 /* /lib works for systems without usr-merge, and for systems with a sane
848 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
849 * for Gentoo which does a merge without making /lib a symlink.
851 "lib/systemd/libsystemd-shared-*.so\0"
852 "usr/lib/systemd/libsystemd-shared-*.so\0") {
854 _cleanup_strv_free_ char **names = NULL;
855 _cleanup_free_ char *path = NULL;
858 path = prefix_root(root, pattern);
862 r = glob_extend(&names, path);
868 assert_se((c = endswith(path, "*.so")));
869 *c = '\0'; /* truncate the glob part */
871 STRV_FOREACH(name, names) {
872 /* This is most likely to run only once, hence let's not optimize anything. */
876 t = startswith(*name, path);
880 t2 = endswith(t, ".so");
884 t2[0] = '\0'; /* truncate the suffix */
886 r = safe_atou(t, &version);
888 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
892 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
894 version >= minimal_version ? "OK" : "too old");
895 if (version >= minimal_version)
904 bool dot_or_dot_dot(const char *path) {