]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/path-util.c
tree-wide: introduce free_and_replace helper
[thirdparty/systemd.git] / src / basic / path-util.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2010-2012 Lennart Poettering
5
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.
10
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.
15
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/>.
18 ***/
19
20 #include <errno.h>
21 #include <limits.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27
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(). */
31 #include <libgen.h>
32 #undef basename
33
34 #include "alloc-util.h"
35 #include "extract-word.h"
36 #include "fs-util.h"
37 #include "glob-util.h"
38 #include "log.h"
39 #include "macro.h"
40 #include "missing.h"
41 #include "parse-util.h"
42 #include "path-util.h"
43 #include "stat-util.h"
44 #include "string-util.h"
45 #include "strv.h"
46 #include "time-util.h"
47
48 bool path_is_absolute(const char *p) {
49 return p[0] == '/';
50 }
51
52 bool is_path(const char *p) {
53 return !!strchr(p, '/');
54 }
55
56 int path_split_and_make_absolute(const char *p, char ***ret) {
57 char **l;
58 int r;
59
60 assert(p);
61 assert(ret);
62
63 l = strv_split(p, ":");
64 if (!l)
65 return -ENOMEM;
66
67 r = path_strv_make_absolute_cwd(l);
68 if (r < 0) {
69 strv_free(l);
70 return r;
71 }
72
73 *ret = l;
74 return r;
75 }
76
77 char *path_make_absolute(const char *p, const char *prefix) {
78 assert(p);
79
80 /* Makes every item in the list an absolute path by prepending
81 * the prefix, if specified and necessary */
82
83 if (path_is_absolute(p) || !prefix)
84 return strdup(p);
85
86 return strjoin(prefix, "/", p, NULL);
87 }
88
89 int path_make_absolute_cwd(const char *p, char **ret) {
90 char *c;
91
92 assert(p);
93 assert(ret);
94
95 /* Similar to path_make_absolute(), but prefixes with the
96 * current working directory. */
97
98 if (path_is_absolute(p))
99 c = strdup(p);
100 else {
101 _cleanup_free_ char *cwd = NULL;
102
103 cwd = get_current_dir_name();
104 if (!cwd)
105 return negative_errno();
106
107 c = strjoin(cwd, "/", p, NULL);
108 }
109 if (!c)
110 return -ENOMEM;
111
112 *ret = c;
113 return 0;
114 }
115
116 int path_make_relative(const char *from_dir, const char *to_path, char **_r) {
117 char *r, *p;
118 unsigned n_parents;
119
120 assert(from_dir);
121 assert(to_path);
122 assert(_r);
123
124 /* Strips the common part, and adds ".." elements as necessary. */
125
126 if (!path_is_absolute(from_dir))
127 return -EINVAL;
128
129 if (!path_is_absolute(to_path))
130 return -EINVAL;
131
132 /* Skip the common part. */
133 for (;;) {
134 size_t a;
135 size_t b;
136
137 from_dir += strspn(from_dir, "/");
138 to_path += strspn(to_path, "/");
139
140 if (!*from_dir) {
141 if (!*to_path)
142 /* from_dir equals to_path. */
143 r = strdup(".");
144 else
145 /* from_dir is a parent directory of to_path. */
146 r = strdup(to_path);
147
148 if (!r)
149 return -ENOMEM;
150
151 path_kill_slashes(r);
152
153 *_r = r;
154 return 0;
155 }
156
157 if (!*to_path)
158 break;
159
160 a = strcspn(from_dir, "/");
161 b = strcspn(to_path, "/");
162
163 if (a != b)
164 break;
165
166 if (memcmp(from_dir, to_path, a) != 0)
167 break;
168
169 from_dir += a;
170 to_path += b;
171 }
172
173 /* If we're here, then "from_dir" has one or more elements that need to
174 * be replaced with "..". */
175
176 /* Count the number of necessary ".." elements. */
177 for (n_parents = 0;;) {
178 from_dir += strspn(from_dir, "/");
179
180 if (!*from_dir)
181 break;
182
183 from_dir += strcspn(from_dir, "/");
184 n_parents++;
185 }
186
187 r = malloc(n_parents * 3 + strlen(to_path) + 1);
188 if (!r)
189 return -ENOMEM;
190
191 for (p = r; n_parents > 0; n_parents--, p += 3)
192 memcpy(p, "../", 3);
193
194 strcpy(p, to_path);
195 path_kill_slashes(r);
196
197 *_r = r;
198 return 0;
199 }
200
201 int path_strv_make_absolute_cwd(char **l) {
202 char **s;
203 int r;
204
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. */
208
209 STRV_FOREACH(s, l) {
210 char *t;
211
212 r = path_make_absolute_cwd(*s, &t);
213 if (r < 0)
214 return r;
215
216 free(*s);
217 *s = t;
218 }
219
220 return 0;
221 }
222
223 char **path_strv_resolve(char **l, const char *prefix) {
224 char **s;
225 unsigned k = 0;
226 bool enomem = false;
227
228 if (strv_isempty(l))
229 return l;
230
231 /* Goes through every item in the string list and canonicalize
232 * the path. This works in place and won't rollback any
233 * changes on failure. */
234
235 STRV_FOREACH(s, l) {
236 char *t, *u;
237 _cleanup_free_ char *orig = NULL;
238
239 if (!path_is_absolute(*s)) {
240 free(*s);
241 continue;
242 }
243
244 if (prefix) {
245 orig = *s;
246 t = strappend(prefix, orig);
247 if (!t) {
248 enomem = true;
249 continue;
250 }
251 } else
252 t = *s;
253
254 errno = 0;
255 u = canonicalize_file_name(t);
256 if (!u) {
257 if (errno == ENOENT) {
258 if (prefix) {
259 u = orig;
260 orig = NULL;
261 free(t);
262 } else
263 u = t;
264 } else {
265 free(t);
266 if (errno == ENOMEM || errno == 0)
267 enomem = true;
268
269 continue;
270 }
271 } else if (prefix) {
272 char *x;
273
274 free(t);
275 x = path_startswith(u, prefix);
276 if (x) {
277 /* restore the slash if it was lost */
278 if (!startswith(x, "/"))
279 *(--x) = '/';
280
281 t = strdup(x);
282 free(u);
283 if (!t) {
284 enomem = true;
285 continue;
286 }
287 u = t;
288 } else {
289 /* canonicalized path goes outside of
290 * prefix, keep the original path instead */
291 free_and_replace(u, orig);
292 }
293 } else
294 free(t);
295
296 l[k++] = u;
297 }
298
299 l[k] = NULL;
300
301 if (enomem)
302 return NULL;
303
304 return l;
305 }
306
307 char **path_strv_resolve_uniq(char **l, const char *prefix) {
308
309 if (strv_isempty(l))
310 return l;
311
312 if (!path_strv_resolve(l, prefix))
313 return NULL;
314
315 return strv_uniq(l);
316 }
317
318 char *path_kill_slashes(char *path) {
319 char *f, *t;
320 bool slash = false;
321
322 /* Removes redundant inner and trailing slashes. Modifies the
323 * passed string in-place.
324 *
325 * ///foo///bar/ becomes /foo/bar
326 */
327
328 for (f = path, t = path; *f; f++) {
329
330 if (*f == '/') {
331 slash = true;
332 continue;
333 }
334
335 if (slash) {
336 slash = false;
337 *(t++) = '/';
338 }
339
340 *(t++) = *f;
341 }
342
343 /* Special rule, if we are talking of the root directory, a
344 trailing slash is good */
345
346 if (t == path && slash)
347 *(t++) = '/';
348
349 *t = 0;
350 return path;
351 }
352
353 char* path_startswith(const char *path, const char *prefix) {
354 assert(path);
355 assert(prefix);
356
357 if ((path[0] == '/') != (prefix[0] == '/'))
358 return NULL;
359
360 for (;;) {
361 size_t a, b;
362
363 path += strspn(path, "/");
364 prefix += strspn(prefix, "/");
365
366 if (*prefix == 0)
367 return (char*) path;
368
369 if (*path == 0)
370 return NULL;
371
372 a = strcspn(path, "/");
373 b = strcspn(prefix, "/");
374
375 if (a != b)
376 return NULL;
377
378 if (memcmp(path, prefix, a) != 0)
379 return NULL;
380
381 path += a;
382 prefix += b;
383 }
384 }
385
386 int path_compare(const char *a, const char *b) {
387 int d;
388
389 assert(a);
390 assert(b);
391
392 /* A relative path and an abolute path must not compare as equal.
393 * Which one is sorted before the other does not really matter.
394 * Here a relative path is ordered before an absolute path. */
395 d = (a[0] == '/') - (b[0] == '/');
396 if (d != 0)
397 return d;
398
399 for (;;) {
400 size_t j, k;
401
402 a += strspn(a, "/");
403 b += strspn(b, "/");
404
405 if (*a == 0 && *b == 0)
406 return 0;
407
408 /* Order prefixes first: "/foo" before "/foo/bar" */
409 if (*a == 0)
410 return -1;
411 if (*b == 0)
412 return 1;
413
414 j = strcspn(a, "/");
415 k = strcspn(b, "/");
416
417 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
418 d = memcmp(a, b, MIN(j, k));
419 if (d != 0)
420 return (d > 0) - (d < 0); /* sign of d */
421
422 /* Sort "/foo/a" before "/foo/aaa" */
423 d = (j > k) - (j < k); /* sign of (j - k) */
424 if (d != 0)
425 return d;
426
427 a += j;
428 b += k;
429 }
430 }
431
432 bool path_equal(const char *a, const char *b) {
433 return path_compare(a, b) == 0;
434 }
435
436 bool path_equal_or_files_same(const char *a, const char *b) {
437 return path_equal(a, b) || files_same(a, b) > 0;
438 }
439
440 char* path_join(const char *root, const char *path, const char *rest) {
441 assert(path);
442
443 if (!isempty(root))
444 return strjoin(root, endswith(root, "/") ? "" : "/",
445 path[0] == '/' ? path+1 : path,
446 rest ? (endswith(path, "/") ? "" : "/") : NULL,
447 rest && rest[0] == '/' ? rest+1 : rest,
448 NULL);
449 else
450 return strjoin(path,
451 rest ? (endswith(path, "/") ? "" : "/") : NULL,
452 rest && rest[0] == '/' ? rest+1 : rest,
453 NULL);
454 }
455
456 int find_binary(const char *name, char **ret) {
457 int last_error, r;
458 const char *p;
459
460 assert(name);
461
462 if (is_path(name)) {
463 if (access(name, X_OK) < 0)
464 return -errno;
465
466 if (ret) {
467 r = path_make_absolute_cwd(name, ret);
468 if (r < 0)
469 return r;
470 }
471
472 return 0;
473 }
474
475 /**
476 * Plain getenv, not secure_getenv, because we want
477 * to actually allow the user to pick the binary.
478 */
479 p = getenv("PATH");
480 if (!p)
481 p = DEFAULT_PATH;
482
483 last_error = -ENOENT;
484
485 for (;;) {
486 _cleanup_free_ char *j = NULL, *element = NULL;
487
488 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
489 if (r < 0)
490 return r;
491 if (r == 0)
492 break;
493
494 if (!path_is_absolute(element))
495 continue;
496
497 j = strjoin(element, "/", name, NULL);
498 if (!j)
499 return -ENOMEM;
500
501 if (access(j, X_OK) >= 0) {
502 /* Found it! */
503
504 if (ret) {
505 *ret = path_kill_slashes(j);
506 j = NULL;
507 }
508
509 return 0;
510 }
511
512 last_error = -errno;
513 }
514
515 return last_error;
516 }
517
518 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
519 bool changed = false;
520 const char* const* i;
521
522 assert(timestamp);
523
524 if (paths == NULL)
525 return false;
526
527 STRV_FOREACH(i, paths) {
528 struct stat stats;
529 usec_t u;
530
531 if (stat(*i, &stats) < 0)
532 continue;
533
534 u = timespec_load(&stats.st_mtim);
535
536 /* first check */
537 if (*timestamp >= u)
538 continue;
539
540 log_debug("timestamp of '%s' changed", *i);
541
542 /* update timestamp */
543 if (update) {
544 *timestamp = u;
545 changed = true;
546 } else
547 return true;
548 }
549
550 return changed;
551 }
552
553 static int binary_is_good(const char *binary) {
554 _cleanup_free_ char *p = NULL, *d = NULL;
555 int r;
556
557 r = find_binary(binary, &p);
558 if (r == -ENOENT)
559 return 0;
560 if (r < 0)
561 return r;
562
563 /* An fsck that is linked to /bin/true is a non-existent
564 * fsck */
565
566 r = readlink_malloc(p, &d);
567 if (r == -EINVAL) /* not a symlink */
568 return 1;
569 if (r < 0)
570 return r;
571
572 return !PATH_IN_SET(d, "true"
573 "/bin/true",
574 "/usr/bin/true",
575 "/dev/null");
576 }
577
578 int fsck_exists(const char *fstype) {
579 const char *checker;
580
581 assert(fstype);
582
583 if (streq(fstype, "auto"))
584 return -EINVAL;
585
586 checker = strjoina("fsck.", fstype);
587 return binary_is_good(checker);
588 }
589
590 int mkfs_exists(const char *fstype) {
591 const char *mkfs;
592
593 assert(fstype);
594
595 if (streq(fstype, "auto"))
596 return -EINVAL;
597
598 mkfs = strjoina("mkfs.", fstype);
599 return binary_is_good(mkfs);
600 }
601
602 char *prefix_root(const char *root, const char *path) {
603 char *n, *p;
604 size_t l;
605
606 /* If root is passed, prefixes path with it. Otherwise returns
607 * it as is. */
608
609 assert(path);
610
611 /* First, drop duplicate prefixing slashes from the path */
612 while (path[0] == '/' && path[1] == '/')
613 path++;
614
615 if (isempty(root) || path_equal(root, "/"))
616 return strdup(path);
617
618 l = strlen(root) + 1 + strlen(path) + 1;
619
620 n = new(char, l);
621 if (!n)
622 return NULL;
623
624 p = stpcpy(n, root);
625
626 while (p > n && p[-1] == '/')
627 p--;
628
629 if (path[0] != '/')
630 *(p++) = '/';
631
632 strcpy(p, path);
633 return n;
634 }
635
636 int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
637 char *p;
638 int r;
639
640 /*
641 * This function is intended to be used in command line
642 * parsers, to handle paths that are passed in. It makes the
643 * path absolute, and reduces it to NULL if omitted or
644 * root (the latter optionally).
645 *
646 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
647 * SUCCESS! Hence, do not pass in uninitialized pointers.
648 */
649
650 if (isempty(path)) {
651 *arg = mfree(*arg);
652 return 0;
653 }
654
655 r = path_make_absolute_cwd(path, &p);
656 if (r < 0)
657 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
658
659 path_kill_slashes(p);
660 if (suppress_root && path_equal(p, "/"))
661 p = mfree(p);
662
663 free(*arg);
664 *arg = p;
665 return 0;
666 }
667
668 char* dirname_malloc(const char *path) {
669 char *d, *dir, *dir2;
670
671 assert(path);
672
673 d = strdup(path);
674 if (!d)
675 return NULL;
676
677 dir = dirname(d);
678 assert(dir);
679
680 if (dir == d)
681 return d;
682
683 dir2 = strdup(dir);
684 free(d);
685
686 return dir2;
687 }
688
689 bool filename_is_valid(const char *p) {
690 const char *e;
691
692 if (isempty(p))
693 return false;
694
695 if (streq(p, "."))
696 return false;
697
698 if (streq(p, ".."))
699 return false;
700
701 e = strchrnul(p, '/');
702 if (*e != 0)
703 return false;
704
705 if (e - p > FILENAME_MAX)
706 return false;
707
708 return true;
709 }
710
711 bool path_is_safe(const char *p) {
712
713 if (isempty(p))
714 return false;
715
716 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
717 return false;
718
719 if (strlen(p)+1 > PATH_MAX)
720 return false;
721
722 /* The following two checks are not really dangerous, but hey, they still are confusing */
723 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
724 return false;
725
726 if (strstr(p, "//"))
727 return false;
728
729 return true;
730 }
731
732 char *file_in_same_dir(const char *path, const char *filename) {
733 char *e, *ret;
734 size_t k;
735
736 assert(path);
737 assert(filename);
738
739 /* This removes the last component of path and appends
740 * filename, unless the latter is absolute anyway or the
741 * former isn't */
742
743 if (path_is_absolute(filename))
744 return strdup(filename);
745
746 e = strrchr(path, '/');
747 if (!e)
748 return strdup(filename);
749
750 k = strlen(filename);
751 ret = new(char, (e + 1 - path) + k + 1);
752 if (!ret)
753 return NULL;
754
755 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
756 return ret;
757 }
758
759 bool hidden_or_backup_file(const char *filename) {
760 const char *p;
761
762 assert(filename);
763
764 if (filename[0] == '.' ||
765 streq(filename, "lost+found") ||
766 streq(filename, "aquota.user") ||
767 streq(filename, "aquota.group") ||
768 endswith(filename, "~"))
769 return true;
770
771 p = strrchr(filename, '.');
772 if (!p)
773 return false;
774
775 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
776 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
777 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
778 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
779 * string. Specifically: there's now:
780 *
781 * The generic suffixes "~" and ".bak" for backup files
782 * The generic prefix "." for hidden files
783 *
784 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
785 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
786 */
787
788 return STR_IN_SET(p + 1,
789 "rpmnew",
790 "rpmsave",
791 "rpmorig",
792 "dpkg-old",
793 "dpkg-new",
794 "dpkg-tmp",
795 "dpkg-dist",
796 "dpkg-bak",
797 "dpkg-backup",
798 "dpkg-remove",
799 "ucf-new",
800 "ucf-old",
801 "ucf-dist",
802 "swp",
803 "bak",
804 "old",
805 "new");
806 }
807
808 bool is_device_path(const char *path) {
809
810 /* Returns true on paths that refer to a device, either in
811 * sysfs or in /dev */
812
813 return path_startswith(path, "/dev/") ||
814 path_startswith(path, "/sys/");
815 }
816
817 bool is_deviceallow_pattern(const char *path) {
818 return path_startswith(path, "/dev/") ||
819 startswith(path, "block-") ||
820 startswith(path, "char-");
821 }
822
823 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
824 const char *pattern;
825 int r;
826
827 /* Try to guess if systemd installation is later than the specified version. This
828 * is hacky and likely to yield false negatives, particularly if the installation
829 * is non-standard. False positives should be relatively rare.
830 */
831
832 NULSTR_FOREACH(pattern,
833 /* /lib works for systems without usr-merge, and for systems with a sane
834 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
835 * for Gentoo which does a merge without making /lib a symlink.
836 */
837 "lib/systemd/libsystemd-shared-*.so\0"
838 "usr/lib/systemd/libsystemd-shared-*.so\0") {
839
840 _cleanup_strv_free_ char **names = NULL;
841 _cleanup_free_ char *path = NULL;
842 char *c, **name;
843
844 path = prefix_root(root, pattern);
845 if (!path)
846 return -ENOMEM;
847
848 r = glob_extend(&names, path);
849 if (r == -ENOENT)
850 continue;
851 if (r < 0)
852 return r;
853
854 assert_se((c = endswith(path, "*.so")));
855 *c = '\0'; /* truncate the glob part */
856
857 STRV_FOREACH(name, names) {
858 /* This is most likely to run only once, hence let's not optimize anything. */
859 char *t, *t2;
860 unsigned version;
861
862 t = startswith(*name, path);
863 if (!t)
864 continue;
865
866 t2 = endswith(t, ".so");
867 if (!t2)
868 continue;
869
870 t2[0] = '\0'; /* truncate the suffix */
871
872 r = safe_atou(t, &version);
873 if (r < 0) {
874 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
875 continue;
876 }
877
878 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
879 *name, version,
880 version >= minimal_version ? "OK" : "too old");
881 if (version >= minimal_version)
882 return true;
883 }
884 }
885
886 return false;
887 }