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