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. */
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. */
150 path_kill_slashes(r);
159 a = strcspn(from_dir, "/");
160 b = strcspn(to_path, "/");
165 if (memcmp(from_dir, to_path, a) != 0)
172 /* If we're here, then "from_dir" has one or more elements that need to
173 * be replaced with "..". */
175 /* Count the number of necessary ".." elements. */
176 for (n_parents = 0;;) {
179 from_dir += strspn(from_dir, "/");
184 w = strcspn(from_dir, "/");
186 /* If this includes ".." we can't do a simple series of "..", refuse */
187 if (w == 2 && from_dir[0] == '.' && from_dir[1] == '.')
190 /* Count number of elements, except if they are "." */
191 if (w != 1 || from_dir[0] != '.')
197 r = new(char, n_parents * 3 + strlen(to_path) + 1);
201 for (p = r; n_parents > 0; n_parents--)
202 p = mempcpy(p, "../", 3);
205 path_kill_slashes(r);
211 int path_strv_make_absolute_cwd(char **l) {
215 /* Goes through every item in the string list and makes it
216 * absolute. This works in place and won't rollback any
217 * changes on failure. */
222 r = path_make_absolute_cwd(*s, &t);
234 char **path_strv_resolve(char **l, const char *root) {
243 /* Goes through every item in the string list and canonicalize
244 * the path. This works in place and won't rollback any
245 * changes on failure. */
248 _cleanup_free_ char *orig = NULL;
251 if (!path_is_absolute(*s)) {
258 t = prefix_root(root, orig);
266 r = chase_symlinks(t, root, 0, &u);
285 x = path_startswith(u, root);
287 /* restore the slash if it was lost */
288 if (!startswith(x, "/"))
299 /* canonicalized path goes outside of
300 * prefix, keep the original path instead */
301 free_and_replace(u, orig);
317 char **path_strv_resolve_uniq(char **l, const char *root) {
322 if (!path_strv_resolve(l, root))
328 char *path_kill_slashes(char *path) {
332 /* Removes redundant inner and trailing slashes. Modifies the
333 * passed string in-place.
335 * ///foo///bar/ becomes /foo/bar
338 for (f = path, t = path; *f; f++) {
353 /* Special rule, if we are talking of the root directory, a
354 trailing slash is good */
356 if (t == path && slash)
363 char* path_startswith(const char *path, const char *prefix) {
367 /* Returns a pointer to the start of the first component after the parts matched by
369 * - both paths are absolute or both paths are relative,
371 * - each component in prefix in turn matches a component in path at the same position.
372 * An empty string will be returned when the prefix and path are equivalent.
374 * Returns NULL otherwise.
377 if ((path[0] == '/') != (prefix[0] == '/'))
383 path += strspn(path, "/");
384 prefix += strspn(prefix, "/");
392 a = strcspn(path, "/");
393 b = strcspn(prefix, "/");
398 if (memcmp(path, prefix, a) != 0)
406 int path_compare(const char *a, const char *b) {
412 /* A relative path and an abolute path must not compare as equal.
413 * Which one is sorted before the other does not really matter.
414 * Here a relative path is ordered before an absolute path. */
415 d = (a[0] == '/') - (b[0] == '/');
425 if (*a == 0 && *b == 0)
428 /* Order prefixes first: "/foo" before "/foo/bar" */
437 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
438 d = memcmp(a, b, MIN(j, k));
440 return (d > 0) - (d < 0); /* sign of d */
442 /* Sort "/foo/a" before "/foo/aaa" */
443 d = (j > k) - (j < k); /* sign of (j - k) */
452 bool path_equal(const char *a, const char *b) {
453 return path_compare(a, b) == 0;
456 bool path_equal_or_files_same(const char *a, const char *b, int flags) {
457 return path_equal(a, b) || files_same(a, b, flags) > 0;
460 char* path_join(const char *root, const char *path, const char *rest) {
464 return strjoin(root, endswith(root, "/") ? "" : "/",
465 path[0] == '/' ? path+1 : path,
466 rest ? (endswith(path, "/") ? "" : "/") : NULL,
467 rest && rest[0] == '/' ? rest+1 : rest);
470 rest ? (endswith(path, "/") ? "" : "/") : NULL,
471 rest && rest[0] == '/' ? rest+1 : rest);
474 int find_binary(const char *name, char **ret) {
481 if (access(name, X_OK) < 0)
485 r = path_make_absolute_cwd(name, ret);
494 * Plain getenv, not secure_getenv, because we want
495 * to actually allow the user to pick the binary.
501 last_error = -ENOENT;
504 _cleanup_free_ char *j = NULL, *element = NULL;
506 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
512 if (!path_is_absolute(element))
515 j = strjoin(element, "/", name);
519 if (access(j, X_OK) >= 0) {
523 *ret = path_kill_slashes(j);
536 #if 0 /// UNNEEDED by elogind
537 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
538 bool changed = false;
539 const char* const* i;
546 STRV_FOREACH(i, paths) {
550 if (stat(*i, &stats) < 0)
553 u = timespec_load(&stats.st_mtim);
559 log_debug("timestamp of '%s' changed", *i);
561 /* update timestamp */
572 static int binary_is_good(const char *binary) {
573 _cleanup_free_ char *p = NULL, *d = NULL;
576 r = find_binary(binary, &p);
582 /* An fsck that is linked to /bin/true is a non-existent
585 r = readlink_malloc(p, &d);
586 if (r == -EINVAL) /* not a symlink */
591 return !PATH_IN_SET(d, "true"
597 int fsck_exists(const char *fstype) {
602 if (streq(fstype, "auto"))
605 checker = strjoina("fsck.", fstype);
606 return binary_is_good(checker);
609 int mkfs_exists(const char *fstype) {
614 if (streq(fstype, "auto"))
617 mkfs = strjoina("mkfs.", fstype);
618 return binary_is_good(mkfs);
622 char *prefix_root(const char *root, const char *path) {
626 /* If root is passed, prefixes path with it. Otherwise returns
631 /* First, drop duplicate prefixing slashes from the path */
632 while (path[0] == '/' && path[1] == '/')
635 if (isempty(root) || path_equal(root, "/"))
638 l = strlen(root) + 1 + strlen(path) + 1;
646 while (p > n && p[-1] == '/')
656 #if 0 /// UNNEEDED by elogind
657 int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
662 * This function is intended to be used in command line
663 * parsers, to handle paths that are passed in. It makes the
664 * path absolute, and reduces it to NULL if omitted or
665 * root (the latter optionally).
667 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
668 * SUCCESS! Hence, do not pass in uninitialized pointers.
676 r = path_make_absolute_cwd(path, &p);
678 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
680 path_kill_slashes(p);
681 if (suppress_root && path_equal(p, "/"))
690 char* dirname_malloc(const char *path) {
691 char *d, *dir, *dir2;
711 bool filename_is_valid(const char *p) {
717 if (dot_or_dot_dot(p))
720 e = strchrnul(p, '/');
724 if (e - p > FILENAME_MAX)
730 bool path_is_safe(const char *p) {
735 if (dot_or_dot_dot(p))
738 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
741 if (strlen(p)+1 > PATH_MAX)
744 /* The following two checks are not really dangerous, but hey, they still are confusing */
745 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
754 char *file_in_same_dir(const char *path, const char *filename) {
761 /* This removes the last component of path and appends
762 * filename, unless the latter is absolute anyway or the
765 if (path_is_absolute(filename))
766 return strdup(filename);
768 e = strrchr(path, '/');
770 return strdup(filename);
772 k = strlen(filename);
773 ret = new(char, (e + 1 - path) + k + 1);
777 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
781 bool hidden_or_backup_file(const char *filename) {
786 if (filename[0] == '.' ||
787 streq(filename, "lost+found") ||
788 streq(filename, "aquota.user") ||
789 streq(filename, "aquota.group") ||
790 endswith(filename, "~"))
793 p = strrchr(filename, '.');
797 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
798 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
799 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
800 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
801 * string. Specifically: there's now:
803 * The generic suffixes "~" and ".bak" for backup files
804 * The generic prefix "." for hidden files
806 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
807 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
810 return STR_IN_SET(p + 1,
830 #if 0 /// UNNEEDED by elogind
831 bool is_device_path(const char *path) {
833 /* Returns true on paths that refer to a device, either in
834 * sysfs or in /dev */
836 return path_startswith(path, "/dev/") ||
837 path_startswith(path, "/sys/");
840 bool is_deviceallow_pattern(const char *path) {
841 return path_startswith(path, "/dev/") ||
842 startswith(path, "block-") ||
843 startswith(path, "char-");
846 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
850 /* Try to guess if systemd installation is later than the specified version. This
851 * is hacky and likely to yield false negatives, particularly if the installation
852 * is non-standard. False positives should be relatively rare.
855 NULSTR_FOREACH(pattern,
856 /* /lib works for systems without usr-merge, and for systems with a sane
857 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
858 * for Gentoo which does a merge without making /lib a symlink.
860 "lib/systemd/libsystemd-shared-*.so\0"
861 "usr/lib/systemd/libsystemd-shared-*.so\0") {
863 _cleanup_strv_free_ char **names = NULL;
864 _cleanup_free_ char *path = NULL;
867 path = prefix_root(root, pattern);
871 r = glob_extend(&names, path);
877 assert_se((c = endswith(path, "*.so")));
878 *c = '\0'; /* truncate the glob part */
880 STRV_FOREACH(name, names) {
881 /* This is most likely to run only once, hence let's not optimize anything. */
885 t = startswith(*name, path);
889 t2 = endswith(t, ".so");
893 t2[0] = '\0'; /* truncate the suffix */
895 r = safe_atou(t, &version);
897 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
901 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
903 version >= minimal_version ? "OK" : "too old");
904 if (version >= minimal_version)
913 bool dot_or_dot_dot(const char *path) {