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 #if 0 /// UNNEEDED by elogind
57 int path_split_and_make_absolute(const char *p, char ***ret) {
64 l = strv_split(p, ":");
68 r = path_strv_make_absolute_cwd(l);
78 char *path_make_absolute(const char *p, const char *prefix) {
81 /* Makes every item in the list an absolute path by prepending
82 * the prefix, if specified and necessary */
84 if (path_is_absolute(p) || !prefix)
87 return strjoin(prefix, "/", p);
91 int path_make_absolute_cwd(const char *p, char **ret) {
97 /* Similar to path_make_absolute(), but prefixes with the
98 * current working directory. */
100 if (path_is_absolute(p))
103 _cleanup_free_ char *cwd = NULL;
105 cwd = get_current_dir_name();
107 return negative_errno();
109 c = strjoin(cwd, "/", p);
118 #if 0 /// UNNEEDED by elogind
119 int path_make_relative(const char *from_dir, const char *to_path, char **_r) {
127 /* Strips the common part, and adds ".." elements as necessary. */
129 if (!path_is_absolute(from_dir))
132 if (!path_is_absolute(to_path))
135 /* Skip the common part. */
139 from_dir += strspn(from_dir, "/");
140 to_path += strspn(to_path, "/");
144 /* from_dir equals to_path. */
147 /* 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;;) {
181 from_dir += strspn(from_dir, "/");
186 w = strcspn(from_dir, "/");
188 /* If this includes ".." we can't do a simple series of "..", refuse */
189 if (w == 2 && from_dir[0] == '.' && from_dir[1] == '.')
192 /* Count number of elements, except if they are "." */
193 if (w != 1 || from_dir[0] != '.')
199 r = new(char, n_parents * 3 + strlen(to_path) + 1);
203 for (p = r; n_parents > 0; n_parents--)
204 p = mempcpy(p, "../", 3);
207 path_kill_slashes(r);
213 int path_strv_make_absolute_cwd(char **l) {
217 /* Goes through every item in the string list and makes it
218 * absolute. This works in place and won't rollback any
219 * changes on failure. */
224 r = path_make_absolute_cwd(*s, &t);
236 char **path_strv_resolve(char **l, const char *root) {
245 /* Goes through every item in the string list and canonicalize
246 * the path. This works in place and won't rollback any
247 * changes on failure. */
250 _cleanup_free_ char *orig = NULL;
253 if (!path_is_absolute(*s)) {
260 t = prefix_root(root, orig);
268 r = chase_symlinks(t, root, 0, &u);
287 x = path_startswith(u, root);
289 /* restore the slash if it was lost */
290 if (!startswith(x, "/"))
301 /* canonicalized path goes outside of
302 * prefix, keep the original path instead */
303 free_and_replace(u, orig);
319 char **path_strv_resolve_uniq(char **l, const char *root) {
324 if (!path_strv_resolve(l, root))
330 char *path_kill_slashes(char *path) {
334 /* Removes redundant inner and trailing slashes. Modifies the
335 * passed string in-place.
337 * ///foo///bar/ becomes /foo/bar
340 for (f = path, t = path; *f; f++) {
355 /* Special rule, if we are talking of the root directory, a
356 trailing slash is good */
358 if (t == path && slash)
365 char* path_startswith(const char *path, const char *prefix) {
369 /* Returns a pointer to the start of the first component after the parts matched by
371 * - both paths are absolute or both paths are relative,
373 * - each component in prefix in turn matches a component in path at the same position.
374 * An empty string will be returned when the prefix and path are equivalent.
376 * Returns NULL otherwise.
379 if ((path[0] == '/') != (prefix[0] == '/'))
385 path += strspn(path, "/");
386 prefix += strspn(prefix, "/");
394 a = strcspn(path, "/");
395 b = strcspn(prefix, "/");
400 if (memcmp(path, prefix, a) != 0)
408 int path_compare(const char *a, const char *b) {
414 /* A relative path and an abolute path must not compare as equal.
415 * Which one is sorted before the other does not really matter.
416 * Here a relative path is ordered before an absolute path. */
417 d = (a[0] == '/') - (b[0] == '/');
427 if (*a == 0 && *b == 0)
430 /* Order prefixes first: "/foo" before "/foo/bar" */
439 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
440 d = memcmp(a, b, MIN(j, k));
442 return (d > 0) - (d < 0); /* sign of d */
444 /* Sort "/foo/a" before "/foo/aaa" */
445 d = (j > k) - (j < k); /* sign of (j - k) */
454 bool path_equal(const char *a, const char *b) {
455 return path_compare(a, b) == 0;
458 bool path_equal_or_files_same(const char *a, const char *b, int flags) {
459 return path_equal(a, b) || files_same(a, b, flags) > 0;
462 char* path_join(const char *root, const char *path, const char *rest) {
466 return strjoin(root, endswith(root, "/") ? "" : "/",
467 path[0] == '/' ? path+1 : path,
468 rest ? (endswith(path, "/") ? "" : "/") : NULL,
469 rest && rest[0] == '/' ? rest+1 : rest);
472 rest ? (endswith(path, "/") ? "" : "/") : NULL,
473 rest && rest[0] == '/' ? rest+1 : rest);
476 int find_binary(const char *name, char **ret) {
483 if (access(name, X_OK) < 0)
487 r = path_make_absolute_cwd(name, ret);
496 * Plain getenv, not secure_getenv, because we want
497 * to actually allow the user to pick the binary.
503 last_error = -ENOENT;
506 _cleanup_free_ char *j = NULL, *element = NULL;
508 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
514 if (!path_is_absolute(element))
517 j = strjoin(element, "/", name);
521 if (access(j, X_OK) >= 0) {
525 *ret = path_kill_slashes(j);
538 #if 0 /// UNNEEDED by elogind
539 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
540 bool changed = false;
541 const char* const* i;
548 STRV_FOREACH(i, paths) {
552 if (stat(*i, &stats) < 0)
555 u = timespec_load(&stats.st_mtim);
561 log_debug("timestamp of '%s' changed", *i);
563 /* update timestamp */
574 static int binary_is_good(const char *binary) {
575 _cleanup_free_ char *p = NULL, *d = NULL;
578 r = find_binary(binary, &p);
584 /* An fsck that is linked to /bin/true is a non-existent
587 r = readlink_malloc(p, &d);
588 if (r == -EINVAL) /* not a symlink */
593 return !PATH_IN_SET(d, "true"
599 int fsck_exists(const char *fstype) {
604 if (streq(fstype, "auto"))
607 checker = strjoina("fsck.", fstype);
608 return binary_is_good(checker);
611 int mkfs_exists(const char *fstype) {
616 if (streq(fstype, "auto"))
619 mkfs = strjoina("mkfs.", fstype);
620 return binary_is_good(mkfs);
624 char *prefix_root(const char *root, const char *path) {
628 /* If root is passed, prefixes path with it. Otherwise returns
633 /* First, drop duplicate prefixing slashes from the path */
634 while (path[0] == '/' && path[1] == '/')
637 if (isempty(root) || path_equal(root, "/"))
640 l = strlen(root) + 1 + strlen(path) + 1;
648 while (p > n && p[-1] == '/')
658 #if 0 /// UNNEEDED by elogind
659 int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
664 * This function is intended to be used in command line
665 * parsers, to handle paths that are passed in. It makes the
666 * path absolute, and reduces it to NULL if omitted or
667 * root (the latter optionally).
669 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
670 * SUCCESS! Hence, do not pass in uninitialized pointers.
678 r = path_make_absolute_cwd(path, &p);
680 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
682 path_kill_slashes(p);
683 if (suppress_root && path_equal(p, "/"))
692 char* dirname_malloc(const char *path) {
693 char *d, *dir, *dir2;
713 bool filename_is_valid(const char *p) {
719 if (dot_or_dot_dot(p))
722 e = strchrnul(p, '/');
726 if (e - p > FILENAME_MAX)
732 bool path_is_safe(const char *p) {
737 if (dot_or_dot_dot(p))
740 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
743 if (strlen(p)+1 > PATH_MAX)
746 /* The following two checks are not really dangerous, but hey, they still are confusing */
747 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
756 char *file_in_same_dir(const char *path, const char *filename) {
763 /* This removes the last component of path and appends
764 * filename, unless the latter is absolute anyway or the
767 if (path_is_absolute(filename))
768 return strdup(filename);
770 e = strrchr(path, '/');
772 return strdup(filename);
774 k = strlen(filename);
775 ret = new(char, (e + 1 - path) + k + 1);
779 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
783 bool hidden_or_backup_file(const char *filename) {
788 if (filename[0] == '.' ||
789 streq(filename, "lost+found") ||
790 streq(filename, "aquota.user") ||
791 streq(filename, "aquota.group") ||
792 endswith(filename, "~"))
795 p = strrchr(filename, '.');
799 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
800 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
801 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
802 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
803 * string. Specifically: there's now:
805 * The generic suffixes "~" and ".bak" for backup files
806 * The generic prefix "." for hidden files
808 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
809 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
812 return STR_IN_SET(p + 1,
832 #if 0 /// UNNEEDED by elogind
833 bool is_device_path(const char *path) {
835 /* Returns true on paths that refer to a device, either in
836 * sysfs or in /dev */
838 return path_startswith(path, "/dev/") ||
839 path_startswith(path, "/sys/");
842 bool is_deviceallow_pattern(const char *path) {
843 return path_startswith(path, "/dev/") ||
844 startswith(path, "block-") ||
845 startswith(path, "char-");
848 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
852 /* Try to guess if systemd installation is later than the specified version. This
853 * is hacky and likely to yield false negatives, particularly if the installation
854 * is non-standard. False positives should be relatively rare.
857 NULSTR_FOREACH(pattern,
858 /* /lib works for systems without usr-merge, and for systems with a sane
859 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
860 * for Gentoo which does a merge without making /lib a symlink.
862 "lib/systemd/libsystemd-shared-*.so\0"
863 "usr/lib/systemd/libsystemd-shared-*.so\0") {
865 _cleanup_strv_free_ char **names = NULL;
866 _cleanup_free_ char *path = NULL;
869 path = prefix_root(root, pattern);
873 r = glob_extend(&names, path);
879 assert_se((c = endswith(path, "*.so")));
880 *c = '\0'; /* truncate the glob part */
882 STRV_FOREACH(name, names) {
883 /* This is most likely to run only once, hence let's not optimize anything. */
887 t = startswith(*name, path);
891 t2 = endswith(t, ".so");
895 t2[0] = '\0'; /* truncate the suffix */
897 r = safe_atou(t, &version);
899 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
903 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
905 version >= minimal_version ? "OK" : "too old");
906 if (version >= minimal_version)
915 bool dot_or_dot_dot(const char *path) {