]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/path-util.c
Merge pull request #33452 from bluca/repart_pkg
[thirdparty/systemd.git] / src / basic / path-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fnmatch.h>
5 #include <limits.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9
10 #include "alloc-util.h"
11 #include "chase.h"
12 #include "extract-word.h"
13 #include "fd-util.h"
14 #include "fs-util.h"
15 #include "glob-util.h"
16 #include "log.h"
17 #include "macro.h"
18 #include "path-util.h"
19 #include "stat-util.h"
20 #include "string-util.h"
21 #include "strv.h"
22 #include "time-util.h"
23
24 int path_split_and_make_absolute(const char *p, char ***ret) {
25 _cleanup_strv_free_ char **l = NULL;
26 int r;
27
28 assert(p);
29 assert(ret);
30
31 l = strv_split(p, ":");
32 if (!l)
33 return -ENOMEM;
34
35 r = path_strv_make_absolute_cwd(l);
36 if (r < 0)
37 return r;
38
39 *ret = TAKE_PTR(l);
40 return r;
41 }
42
43 char* path_make_absolute(const char *p, const char *prefix) {
44 assert(p);
45
46 /* Makes every item in the list an absolute path by prepending
47 * the prefix, if specified and necessary */
48
49 if (path_is_absolute(p) || isempty(prefix))
50 return strdup(p);
51
52 return path_join(prefix, p);
53 }
54
55 int safe_getcwd(char **ret) {
56 _cleanup_free_ char *cwd = NULL;
57
58 cwd = get_current_dir_name();
59 if (!cwd)
60 return negative_errno();
61
62 /* Let's make sure the directory is really absolute, to protect us from the logic behind
63 * CVE-2018-1000001 */
64 if (cwd[0] != '/')
65 return -ENOMEDIUM;
66
67 if (ret)
68 *ret = TAKE_PTR(cwd);
69
70 return 0;
71 }
72
73 int path_make_absolute_cwd(const char *p, char **ret) {
74 char *c;
75 int r;
76
77 assert(p);
78 assert(ret);
79
80 /* Similar to path_make_absolute(), but prefixes with the
81 * current working directory. */
82
83 if (path_is_absolute(p))
84 c = strdup(p);
85 else {
86 _cleanup_free_ char *cwd = NULL;
87
88 r = safe_getcwd(&cwd);
89 if (r < 0)
90 return r;
91
92 c = path_join(cwd, p);
93 }
94 if (!c)
95 return -ENOMEM;
96
97 *ret = c;
98 return 0;
99 }
100
101 int path_make_relative(const char *from, const char *to, char **ret) {
102 _cleanup_free_ char *result = NULL;
103 unsigned n_parents;
104 const char *f, *t;
105 int r, k;
106 char *p;
107
108 assert(from);
109 assert(to);
110 assert(ret);
111
112 /* Strips the common part, and adds ".." elements as necessary. */
113
114 if (!path_is_absolute(from) || !path_is_absolute(to))
115 return -EINVAL;
116
117 for (;;) {
118 r = path_find_first_component(&from, true, &f);
119 if (r < 0)
120 return r;
121
122 k = path_find_first_component(&to, true, &t);
123 if (k < 0)
124 return k;
125
126 if (r == 0) {
127 /* end of 'from' */
128 if (k == 0) {
129 /* from and to are equivalent. */
130 result = strdup(".");
131 if (!result)
132 return -ENOMEM;
133 } else {
134 /* 'to' is inside of 'from'. */
135 r = path_simplify_alloc(t, &result);
136 if (r < 0)
137 return r;
138
139 if (!path_is_valid(result))
140 return -EINVAL;
141 }
142
143 *ret = TAKE_PTR(result);
144 return 0;
145 }
146
147 if (r != k || !strneq(f, t, r))
148 break;
149 }
150
151 /* If we're here, then "from_dir" has one or more elements that need to
152 * be replaced with "..". */
153
154 for (n_parents = 1;; n_parents++) {
155 /* If this includes ".." we can't do a simple series of "..". */
156 r = path_find_first_component(&from, false, &f);
157 if (r < 0)
158 return r;
159 if (r == 0)
160 break;
161 }
162
163 if (isempty(t) && n_parents * 3 > PATH_MAX)
164 /* PATH_MAX is counted *with* the trailing NUL byte */
165 return -EINVAL;
166
167 result = new(char, n_parents * 3 + !isempty(t) + strlen_ptr(t));
168 if (!result)
169 return -ENOMEM;
170
171 for (p = result; n_parents > 0; n_parents--)
172 p = mempcpy(p, "../", 3);
173
174 if (isempty(t)) {
175 /* Remove trailing slash and terminate string. */
176 *(--p) = '\0';
177 *ret = TAKE_PTR(result);
178 return 0;
179 }
180
181 strcpy(p, t);
182
183 path_simplify(result);
184
185 if (!path_is_valid(result))
186 return -EINVAL;
187
188 *ret = TAKE_PTR(result);
189 return 0;
190 }
191
192 int path_make_relative_parent(const char *from_child, const char *to, char **ret) {
193 _cleanup_free_ char *from = NULL;
194 int r;
195
196 assert(from_child);
197 assert(to);
198 assert(ret);
199
200 /* Similar to path_make_relative(), but provides the relative path from the parent directory of
201 * 'from_child'. This may be useful when creating relative symlink.
202 *
203 * E.g.
204 * - from = "/path/to/aaa", to = "/path/to/bbb"
205 * path_make_relative(from, to) = "../bbb"
206 * path_make_relative_parent(from, to) = "bbb"
207 *
208 * - from = "/path/to/aaa/bbb", to = "/path/to/ccc/ddd"
209 * path_make_relative(from, to) = "../../ccc/ddd"
210 * path_make_relative_parent(from, to) = "../ccc/ddd"
211 */
212
213 r = path_extract_directory(from_child, &from);
214 if (r < 0)
215 return r;
216
217 return path_make_relative(from, to, ret);
218 }
219
220 char* path_startswith_strv(const char *p, char * const *strv) {
221 assert(p);
222
223 STRV_FOREACH(s, strv) {
224 char *t;
225
226 t = path_startswith(p, *s);
227 if (t)
228 return t;
229 }
230
231 return NULL;
232 }
233
234 int path_strv_make_absolute_cwd(char **l) {
235 int r;
236
237 /* Goes through every item in the string list and makes it
238 * absolute. This works in place and won't rollback any
239 * changes on failure. */
240
241 STRV_FOREACH(s, l) {
242 char *t;
243
244 r = path_make_absolute_cwd(*s, &t);
245 if (r < 0)
246 return r;
247
248 path_simplify(t);
249 free_and_replace(*s, t);
250 }
251
252 return 0;
253 }
254
255 char** path_strv_resolve(char **l, const char *root) {
256 unsigned k = 0;
257 bool enomem = false;
258 int r;
259
260 if (strv_isempty(l))
261 return l;
262
263 /* Goes through every item in the string list and canonicalize
264 * the path. This works in place and won't rollback any
265 * changes on failure. */
266
267 STRV_FOREACH(s, l) {
268 _cleanup_free_ char *orig = NULL;
269 char *t, *u;
270
271 if (!path_is_absolute(*s)) {
272 free(*s);
273 continue;
274 }
275
276 if (root) {
277 orig = *s;
278 t = path_join(root, orig);
279 if (!t) {
280 enomem = true;
281 continue;
282 }
283 } else
284 t = *s;
285
286 r = chase(t, root, 0, &u, NULL);
287 if (r == -ENOENT) {
288 if (root) {
289 u = TAKE_PTR(orig);
290 free(t);
291 } else
292 u = t;
293 } else if (r < 0) {
294 free(t);
295
296 if (r == -ENOMEM)
297 enomem = true;
298
299 continue;
300 } else if (root) {
301 char *x;
302
303 free(t);
304 x = path_startswith(u, root);
305 if (x) {
306 /* restore the slash if it was lost */
307 if (!startswith(x, "/"))
308 *(--x) = '/';
309
310 t = strdup(x);
311 free(u);
312 if (!t) {
313 enomem = true;
314 continue;
315 }
316 u = t;
317 } else {
318 /* canonicalized path goes outside of
319 * prefix, keep the original path instead */
320 free_and_replace(u, orig);
321 }
322 } else
323 free(t);
324
325 l[k++] = u;
326 }
327
328 l[k] = NULL;
329
330 if (enomem)
331 return NULL;
332
333 return l;
334 }
335
336 char** path_strv_resolve_uniq(char **l, const char *root) {
337
338 if (strv_isempty(l))
339 return l;
340
341 if (!path_strv_resolve(l, root))
342 return NULL;
343
344 return strv_uniq(l);
345 }
346
347 char* path_simplify_full(char *path, PathSimplifyFlags flags) {
348 bool add_slash = false, keep_trailing_slash, absolute, beginning = true;
349 char *f = path;
350 int r;
351
352 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots.
353 * Modifies the passed string in-place.
354 *
355 * ///foo//./bar/. becomes /foo/bar
356 * .//./foo//./bar/. becomes foo/bar
357 * /../foo/bar becomes /foo/bar
358 * /../foo/bar/.. becomes /foo/bar/..
359 */
360
361 if (isempty(path))
362 return path;
363
364 keep_trailing_slash = FLAGS_SET(flags, PATH_SIMPLIFY_KEEP_TRAILING_SLASH) && endswith(path, "/");
365
366 absolute = path_is_absolute(path);
367 f += absolute; /* Keep leading /, if present. */
368
369 for (const char *p = f;;) {
370 const char *e;
371
372 r = path_find_first_component(&p, true, &e);
373 if (r == 0)
374 break;
375
376 if (r > 0 && absolute && beginning && path_startswith(e, ".."))
377 /* If we're at the beginning of an absolute path, we can safely skip ".." */
378 continue;
379
380 beginning = false;
381
382 if (add_slash)
383 *f++ = '/';
384
385 if (r < 0) {
386 /* if path is invalid, then refuse to simplify the remaining part. */
387 memmove(f, p, strlen(p) + 1);
388 return path;
389 }
390
391 memmove(f, e, r);
392 f += r;
393
394 add_slash = true;
395 }
396
397 /* Special rule, if we stripped everything, we need a "." for the current directory. */
398 if (f == path)
399 *f++ = '.';
400
401 if (*(f-1) != '/' && keep_trailing_slash)
402 *f++ = '/';
403
404 *f = '\0';
405 return path;
406 }
407
408 char* path_startswith_full(const char *path, const char *prefix, bool accept_dot_dot) {
409 assert(path);
410 assert(prefix);
411
412 /* Returns a pointer to the start of the first component after the parts matched by
413 * the prefix, iff
414 * - both paths are absolute or both paths are relative,
415 * and
416 * - each component in prefix in turn matches a component in path at the same position.
417 * An empty string will be returned when the prefix and path are equivalent.
418 *
419 * Returns NULL otherwise.
420 */
421
422 if ((path[0] == '/') != (prefix[0] == '/'))
423 return NULL;
424
425 for (;;) {
426 const char *p, *q;
427 int r, k;
428
429 r = path_find_first_component(&path, accept_dot_dot, &p);
430 if (r < 0)
431 return NULL;
432
433 k = path_find_first_component(&prefix, accept_dot_dot, &q);
434 if (k < 0)
435 return NULL;
436
437 if (k == 0)
438 return (char*) (p ?: path);
439
440 if (r != k)
441 return NULL;
442
443 if (!strneq(p, q, r))
444 return NULL;
445 }
446 }
447
448 int path_compare(const char *a, const char *b) {
449 int r;
450
451 /* Order NULL before non-NULL */
452 r = CMP(!!a, !!b);
453 if (r != 0)
454 return r;
455
456 /* A relative path and an absolute path must not compare as equal.
457 * Which one is sorted before the other does not really matter.
458 * Here a relative path is ordered before an absolute path. */
459 r = CMP(path_is_absolute(a), path_is_absolute(b));
460 if (r != 0)
461 return r;
462
463 for (;;) {
464 const char *aa, *bb;
465 int j, k;
466
467 j = path_find_first_component(&a, true, &aa);
468 k = path_find_first_component(&b, true, &bb);
469
470 if (j < 0 || k < 0) {
471 /* When one of paths is invalid, order invalid path after valid one. */
472 r = CMP(j < 0, k < 0);
473 if (r != 0)
474 return r;
475
476 /* fallback to use strcmp() if both paths are invalid. */
477 return strcmp(a, b);
478 }
479
480 /* Order prefixes first: "/foo" before "/foo/bar" */
481 if (j == 0) {
482 if (k == 0)
483 return 0;
484 return -1;
485 }
486 if (k == 0)
487 return 1;
488
489 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
490 r = memcmp(aa, bb, MIN(j, k));
491 if (r != 0)
492 return r;
493
494 /* Sort "/foo/a" before "/foo/aaa" */
495 r = CMP(j, k);
496 if (r != 0)
497 return r;
498 }
499 }
500
501 int path_compare_filename(const char *a, const char *b) {
502 _cleanup_free_ char *fa = NULL, *fb = NULL;
503 int r, j, k;
504
505 /* Order NULL before non-NULL */
506 r = CMP(!!a, !!b);
507 if (r != 0)
508 return r;
509
510 j = path_extract_filename(a, &fa);
511 k = path_extract_filename(b, &fb);
512
513 /* When one of paths is "." or root, then order it earlier. */
514 r = CMP(j != -EADDRNOTAVAIL, k != -EADDRNOTAVAIL);
515 if (r != 0)
516 return r;
517
518 /* When one of paths is invalid (or we get OOM), order invalid path after valid one. */
519 r = CMP(j < 0, k < 0);
520 if (r != 0)
521 return r;
522
523 /* fallback to use strcmp() if both paths are invalid. */
524 if (j < 0)
525 return strcmp(a, b);
526
527 return strcmp(fa, fb);
528 }
529
530 int path_equal_or_inode_same_full(const char *a, const char *b, int flags) {
531 /* Returns true if paths are of the same entry, false if not, <0 on error. */
532
533 if (path_equal(a, b))
534 return 1;
535
536 if (!a || !b)
537 return 0;
538
539 return inode_same(a, b, flags);
540 }
541
542 char* path_extend_internal(char **x, ...) {
543 size_t sz, old_sz;
544 char *q, *nx;
545 const char *p;
546 va_list ap;
547 bool slash;
548
549 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings
550 * end/begin already with one so that it is unnecessary. Note that slashes which are already
551 * duplicate won't be removed. The string returned is hence always equal to or longer than the sum of
552 * the lengths of the individual strings.
553 *
554 * The first argument may be an already allocated string that is extended via realloc() if
555 * non-NULL. path_extend() and path_join() are macro wrappers around this function, making use of the
556 * first parameter to distinguish the two operations.
557 *
558 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of
559 * which some are optional.
560 *
561 * Examples:
562 *
563 * path_join("foo", "bar") → "foo/bar"
564 * path_join("foo/", "bar") → "foo/bar"
565 * path_join("", "foo", "", "bar", "") → "foo/bar" */
566
567 sz = old_sz = x ? strlen_ptr(*x) : 0;
568 va_start(ap, x);
569 while ((p = va_arg(ap, char*)) != POINTER_MAX) {
570 size_t add;
571
572 if (isempty(p))
573 continue;
574
575 add = 1 + strlen(p);
576 if (sz > SIZE_MAX - add) { /* overflow check */
577 va_end(ap);
578 return NULL;
579 }
580
581 sz += add;
582 }
583 va_end(ap);
584
585 nx = realloc(x ? *x : NULL, GREEDY_ALLOC_ROUND_UP(sz+1));
586 if (!nx)
587 return NULL;
588 if (x)
589 *x = nx;
590
591 if (old_sz > 0)
592 slash = nx[old_sz-1] == '/';
593 else {
594 nx[old_sz] = 0;
595 slash = true; /* no need to generate a slash anymore */
596 }
597
598 q = nx + old_sz;
599
600 va_start(ap, x);
601 while ((p = va_arg(ap, char*)) != POINTER_MAX) {
602 if (isempty(p))
603 continue;
604
605 if (!slash && p[0] != '/')
606 *(q++) = '/';
607
608 q = stpcpy(q, p);
609 slash = endswith(p, "/");
610 }
611 va_end(ap);
612
613 return nx;
614 }
615
616 static int check_x_access(const char *path, int *ret_fd) {
617 _cleanup_close_ int fd = -EBADF;
618 int r;
619
620 /* We need to use O_PATH because there may be executables for which we have only exec
621 * permissions, but not read (usually suid executables). */
622 fd = open(path, O_PATH|O_CLOEXEC);
623 if (fd < 0)
624 return -errno;
625
626 r = fd_verify_regular(fd);
627 if (r < 0)
628 return r;
629
630 r = access_fd(fd, X_OK);
631 if (r == -ENOSYS) {
632 /* /proc is not mounted. Fallback to access(). */
633 if (access(path, X_OK) < 0)
634 return -errno;
635 } else if (r < 0)
636 return r;
637
638 if (ret_fd)
639 *ret_fd = TAKE_FD(fd);
640
641 return 0;
642 }
643
644 static int find_executable_impl(const char *name, const char *root, char **ret_filename, int *ret_fd) {
645 _cleanup_close_ int fd = -EBADF;
646 _cleanup_free_ char *path_name = NULL;
647 int r;
648
649 assert(name);
650
651 /* Function chase() is invoked only when root is not NULL, as using it regardless of
652 * root value would alter the behavior of existing callers for example: /bin/sleep would become
653 * /usr/bin/sleep when find_executables is called. Hence, this function should be invoked when
654 * needed to avoid unforeseen regression or other complicated changes. */
655 if (root) {
656 /* prefix root to name in case full paths are not specified */
657 r = chase(name, root, CHASE_PREFIX_ROOT, &path_name, /* ret_fd= */ NULL);
658 if (r < 0)
659 return r;
660
661 name = path_name;
662 }
663
664 r = check_x_access(name, ret_fd ? &fd : NULL);
665 if (r < 0)
666 return r;
667
668 if (ret_filename) {
669 r = path_make_absolute_cwd(name, ret_filename);
670 if (r < 0)
671 return r;
672 }
673
674 if (ret_fd)
675 *ret_fd = TAKE_FD(fd);
676
677 return 0;
678 }
679
680 int find_executable_full(
681 const char *name,
682 const char *root,
683 char **exec_search_path,
684 bool use_path_envvar,
685 char **ret_filename,
686 int *ret_fd) {
687
688 int last_error = -ENOENT, r = 0;
689 const char *p = NULL;
690
691 assert(name);
692
693 if (is_path(name))
694 return find_executable_impl(name, root, ret_filename, ret_fd);
695
696 if (use_path_envvar)
697 /* Plain getenv, not secure_getenv, because we want to actually allow the user to pick the
698 * binary. */
699 p = getenv("PATH");
700 if (!p)
701 p = default_PATH();
702
703 if (exec_search_path) {
704 STRV_FOREACH(element, exec_search_path) {
705 _cleanup_free_ char *full_path = NULL;
706
707 if (!path_is_absolute(*element))
708 continue;
709
710 full_path = path_join(*element, name);
711 if (!full_path)
712 return -ENOMEM;
713
714 r = find_executable_impl(full_path, root, ret_filename, ret_fd);
715 if (r < 0) {
716 if (r != -EACCES)
717 last_error = r;
718 continue;
719 }
720 return 0;
721 }
722 return last_error;
723 }
724
725 /* Resolve a single-component name to a full path */
726 for (;;) {
727 _cleanup_free_ char *element = NULL;
728
729 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
730 if (r < 0)
731 return r;
732 if (r == 0)
733 break;
734
735 if (!path_is_absolute(element))
736 continue;
737
738 if (!path_extend(&element, name))
739 return -ENOMEM;
740
741 r = find_executable_impl(element, root, ret_filename, ret_fd);
742 if (r < 0) {
743 /* PATH entries which we don't have access to are ignored, as per tradition. */
744 if (r != -EACCES)
745 last_error = r;
746 continue;
747 }
748
749 /* Found it! */
750 return 0;
751 }
752
753 return last_error;
754 }
755
756 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
757 bool changed = false, originally_unset;
758
759 assert(timestamp);
760
761 if (!paths)
762 return false;
763
764 originally_unset = *timestamp == 0;
765
766 STRV_FOREACH(i, paths) {
767 struct stat stats;
768 usec_t u;
769
770 if (stat(*i, &stats) < 0)
771 continue;
772
773 u = timespec_load(&stats.st_mtim);
774
775 /* check first */
776 if (*timestamp >= u)
777 continue;
778
779 log_debug(originally_unset ? "Loaded timestamp for '%s'." : "Timestamp of '%s' changed.", *i);
780
781 /* update timestamp */
782 if (update) {
783 *timestamp = u;
784 changed = true;
785 } else
786 return true;
787 }
788
789 return changed;
790 }
791
792 static int executable_is_good(const char *executable) {
793 _cleanup_free_ char *p = NULL, *d = NULL;
794 int r;
795
796 r = find_executable(executable, &p);
797 if (r == -ENOENT)
798 return 0;
799 if (r < 0)
800 return r;
801
802 /* An fsck that is linked to /bin/true is a non-existent fsck */
803
804 r = readlink_malloc(p, &d);
805 if (r == -EINVAL) /* not a symlink */
806 return 1;
807 if (r < 0)
808 return r;
809
810 return !PATH_IN_SET(d, "true"
811 "/bin/true",
812 "/usr/bin/true",
813 "/dev/null");
814 }
815
816 int fsck_exists(void) {
817 return executable_is_good("fsck");
818 }
819
820 int fsck_exists_for_fstype(const char *fstype) {
821 const char *checker;
822 int r;
823
824 assert(fstype);
825
826 if (streq(fstype, "auto"))
827 return -EINVAL;
828
829 r = fsck_exists();
830 if (r <= 0)
831 return r;
832
833 checker = strjoina("fsck.", fstype);
834 return executable_is_good(checker);
835 }
836
837 static const char* skip_slash_or_dot(const char *p) {
838 for (; !isempty(p); p++) {
839 if (*p == '/')
840 continue;
841 if (startswith(p, "./")) {
842 p++;
843 continue;
844 }
845 break;
846 }
847 return p;
848 }
849
850 int path_find_first_component(const char **p, bool accept_dot_dot, const char **ret) {
851 const char *q, *first, *end_first, *next;
852 size_t len;
853
854 assert(p);
855
856 /* When a path is input, then returns the pointer to the first component and its length, and
857 * move the input pointer to the next component or nul. This skips both over any '/'
858 * immediately *before* and *after* the first component before returning.
859 *
860 * Examples
861 * Input: p: "//.//aaa///bbbbb/cc"
862 * Output: p: "bbbbb///cc"
863 * ret: "aaa///bbbbb/cc"
864 * return value: 3 (== strlen("aaa"))
865 *
866 * Input: p: "aaa//"
867 * Output: p: (pointer to NUL)
868 * ret: "aaa//"
869 * return value: 3 (== strlen("aaa"))
870 *
871 * Input: p: "/", ".", ""
872 * Output: p: (pointer to NUL)
873 * ret: NULL
874 * return value: 0
875 *
876 * Input: p: NULL
877 * Output: p: NULL
878 * ret: NULL
879 * return value: 0
880 *
881 * Input: p: "(too long component)"
882 * Output: return value: -EINVAL
883 *
884 * (when accept_dot_dot is false)
885 * Input: p: "//..//aaa///bbbbb/cc"
886 * Output: return value: -EINVAL
887 */
888
889 q = *p;
890
891 first = skip_slash_or_dot(q);
892 if (isempty(first)) {
893 *p = first;
894 if (ret)
895 *ret = NULL;
896 return 0;
897 }
898 if (streq(first, ".")) {
899 *p = first + 1;
900 if (ret)
901 *ret = NULL;
902 return 0;
903 }
904
905 end_first = strchrnul(first, '/');
906 len = end_first - first;
907
908 if (len > NAME_MAX)
909 return -EINVAL;
910 if (!accept_dot_dot && len == 2 && first[0] == '.' && first[1] == '.')
911 return -EINVAL;
912
913 next = skip_slash_or_dot(end_first);
914
915 *p = next + streq(next, ".");
916 if (ret)
917 *ret = first;
918 return len;
919 }
920
921 static const char* skip_slash_or_dot_backward(const char *path, const char *q) {
922 assert(path);
923 assert(!q || q >= path);
924
925 for (; q; q = PTR_SUB1(q, path)) {
926 if (*q == '/')
927 continue;
928 if (q > path && strneq(q - 1, "/.", 2))
929 continue;
930 if (q == path && *q == '.')
931 continue;
932 break;
933 }
934 return q;
935 }
936
937 int path_find_last_component(const char *path, bool accept_dot_dot, const char **next, const char **ret) {
938 const char *q, *last_end, *last_begin;
939 size_t len;
940
941 /* Similar to path_find_first_component(), but search components from the end.
942 *
943 * Examples
944 * Input: path: "//.//aaa///bbbbb/cc//././"
945 * next: NULL
946 * Output: next: "/cc//././"
947 * ret: "cc//././"
948 * return value: 2 (== strlen("cc"))
949 *
950 * Input: path: "//.//aaa///bbbbb/cc//././"
951 * next: "/cc//././"
952 * Output: next: "///bbbbb/cc//././"
953 * ret: "bbbbb/cc//././"
954 * return value: 5 (== strlen("bbbbb"))
955 *
956 * Input: path: "//.//aaa///bbbbb/cc//././"
957 * next: "///bbbbb/cc//././"
958 * Output: next: "//.//aaa///bbbbb/cc//././" (next == path)
959 * ret: "aaa///bbbbb/cc//././"
960 * return value: 3 (== strlen("aaa"))
961 *
962 * Input: path: "/", ".", "", or NULL
963 * Output: next: equivalent to path
964 * ret: NULL
965 * return value: 0
966 *
967 * Input: path: "(too long component)"
968 * Output: return value: -EINVAL
969 *
970 * (when accept_dot_dot is false)
971 * Input: path: "//..//aaa///bbbbb/cc/..//"
972 * Output: return value: -EINVAL
973 */
974
975 if (isempty(path)) {
976 if (next)
977 *next = path;
978 if (ret)
979 *ret = NULL;
980 return 0;
981 }
982
983 if (next && *next) {
984 if (*next < path || *next > path + strlen(path))
985 return -EINVAL;
986 if (*next == path) {
987 if (ret)
988 *ret = NULL;
989 return 0;
990 }
991 if (!IN_SET(**next, '\0', '/'))
992 return -EINVAL;
993 q = *next - 1;
994 } else
995 q = path + strlen(path) - 1;
996
997 q = skip_slash_or_dot_backward(path, q);
998 if (!q || /* the root directory */
999 (q == path && *q == '.')) { /* path is "." or "./" */
1000 if (next)
1001 *next = path;
1002 if (ret)
1003 *ret = NULL;
1004 return 0;
1005 }
1006
1007 last_end = q + 1;
1008
1009 while (q && *q != '/')
1010 q = PTR_SUB1(q, path);
1011
1012 last_begin = q ? q + 1 : path;
1013 len = last_end - last_begin;
1014
1015 if (len > NAME_MAX)
1016 return -EINVAL;
1017 if (!accept_dot_dot && len == 2 && strneq(last_begin, "..", 2))
1018 return -EINVAL;
1019
1020 if (next) {
1021 q = skip_slash_or_dot_backward(path, q);
1022 *next = q ? q + 1 : path;
1023 }
1024
1025 if (ret)
1026 *ret = last_begin;
1027 return len;
1028 }
1029
1030 const char* last_path_component(const char *path) {
1031
1032 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
1033 *
1034 * a/b/c → c
1035 * a/b/c/ → c/
1036 * x → x
1037 * x/ → x/
1038 * /y → y
1039 * /y/ → y/
1040 * / → /
1041 * // → /
1042 * /foo/a → a
1043 * /foo/a/ → a/
1044 *
1045 * Also, the empty string is mapped to itself.
1046 *
1047 * This is different than basename(), which returns "" when a trailing slash is present.
1048 *
1049 * This always succeeds (except if you pass NULL in which case it returns NULL, too).
1050 */
1051
1052 unsigned l, k;
1053
1054 if (!path)
1055 return NULL;
1056
1057 l = k = strlen(path);
1058 if (l == 0) /* special case — an empty string */
1059 return path;
1060
1061 while (k > 0 && path[k-1] == '/')
1062 k--;
1063
1064 if (k == 0) /* the root directory */
1065 return path + l - 1;
1066
1067 while (k > 0 && path[k-1] != '/')
1068 k--;
1069
1070 return path + k;
1071 }
1072
1073 int path_extract_filename(const char *path, char **ret) {
1074 _cleanup_free_ char *a = NULL;
1075 const char *c, *next = NULL;
1076 int r;
1077
1078 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
1079 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing
1080 * slashes. Returns:
1081 *
1082 * -EINVAL → if the path is not valid
1083 * -EADDRNOTAVAIL → if only a directory was specified, but no filename, i.e. the root dir
1084 * itself or "." is specified
1085 * -ENOMEM → no memory
1086 *
1087 * Returns >= 0 on success. If the input path has a trailing slash, returns O_DIRECTORY, to
1088 * indicate the referenced file must be a directory.
1089 *
1090 * This function guarantees to return a fully valid filename, i.e. one that passes
1091 * filename_is_valid() – this means "." and ".." are not accepted. */
1092
1093 if (!path_is_valid(path))
1094 return -EINVAL;
1095
1096 r = path_find_last_component(path, false, &next, &c);
1097 if (r < 0)
1098 return r;
1099 if (r == 0) /* root directory */
1100 return -EADDRNOTAVAIL;
1101
1102 a = strndup(c, r);
1103 if (!a)
1104 return -ENOMEM;
1105
1106 *ret = TAKE_PTR(a);
1107 return strlen(c) > (size_t) r ? O_DIRECTORY : 0;
1108 }
1109
1110 int path_extract_directory(const char *path, char **ret) {
1111 const char *c, *next = NULL;
1112 int r;
1113
1114 /* The inverse of path_extract_filename(), i.e. returns the directory path prefix. Returns:
1115 *
1116 * -EINVAL → if the path is not valid
1117 * -EDESTADDRREQ → if no directory was specified in the passed in path, i.e. only a filename was passed
1118 * -EADDRNOTAVAIL → if the passed in parameter had no filename but did have a directory, i.e.
1119 * the root dir itself or "." was specified
1120 * -ENOMEM → no memory (surprise!)
1121 *
1122 * This function guarantees to return a fully valid path, i.e. one that passes path_is_valid().
1123 */
1124
1125 r = path_find_last_component(path, false, &next, &c);
1126 if (r < 0)
1127 return r;
1128 if (r == 0) /* empty or root */
1129 return isempty(path) ? -EINVAL : -EADDRNOTAVAIL;
1130 if (next == path) {
1131 if (*path != '/') /* filename only */
1132 return -EDESTADDRREQ;
1133
1134 return strdup_to(ret, "/");
1135 }
1136
1137 _cleanup_free_ char *a = strndup(path, next - path);
1138 if (!a)
1139 return -ENOMEM;
1140
1141 path_simplify(a);
1142
1143 if (!path_is_valid(a))
1144 return -EINVAL;
1145
1146 if (ret)
1147 *ret = TAKE_PTR(a);
1148
1149 return 0;
1150 }
1151
1152 bool filename_part_is_valid(const char *p) {
1153 const char *e;
1154
1155 /* Checks f the specified string is OK to be *part* of a filename. This is different from
1156 * filename_is_valid() as "." and ".." and "" are OK by this call, but not by filename_is_valid(). */
1157
1158 if (!p)
1159 return false;
1160
1161 e = strchrnul(p, '/');
1162 if (*e != 0)
1163 return false;
1164
1165 if (e - p > NAME_MAX) /* NAME_MAX is counted *without* the trailing NUL byte */
1166 return false;
1167
1168 return true;
1169 }
1170
1171 bool filename_is_valid(const char *p) {
1172
1173 if (isempty(p))
1174 return false;
1175
1176 if (dot_or_dot_dot(p)) /* Yes, in this context we consider "." and ".." invalid */
1177 return false;
1178
1179 return filename_part_is_valid(p);
1180 }
1181
1182 bool path_is_valid_full(const char *p, bool accept_dot_dot) {
1183 if (isempty(p))
1184 return false;
1185
1186 for (const char *e = p;;) {
1187 int r;
1188
1189 r = path_find_first_component(&e, accept_dot_dot, NULL);
1190 if (r < 0)
1191 return false;
1192
1193 if (e - p >= PATH_MAX) /* Already reached the maximum length for a path? (PATH_MAX is counted
1194 * *with* the trailing NUL byte) */
1195 return false;
1196 if (*e == 0) /* End of string? Yay! */
1197 return true;
1198 }
1199 }
1200
1201 bool path_is_normalized(const char *p) {
1202 if (!path_is_safe(p))
1203 return false;
1204
1205 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
1206 return false;
1207
1208 if (strstr(p, "//"))
1209 return false;
1210
1211 return true;
1212 }
1213
1214 int file_in_same_dir(const char *path, const char *filename, char **ret) {
1215 _cleanup_free_ char *b = NULL;
1216 int r;
1217
1218 assert(path);
1219 assert(filename);
1220 assert(ret);
1221
1222 /* This removes the last component of path and appends filename, unless the latter is absolute anyway
1223 * or the former isn't */
1224
1225 if (path_is_absolute(filename))
1226 b = strdup(filename);
1227 else {
1228 _cleanup_free_ char *dn = NULL;
1229
1230 r = path_extract_directory(path, &dn);
1231 if (r == -EDESTADDRREQ) /* no path prefix */
1232 b = strdup(filename);
1233 else if (r < 0)
1234 return r;
1235 else
1236 b = path_join(dn, filename);
1237 }
1238 if (!b)
1239 return -ENOMEM;
1240
1241 *ret = TAKE_PTR(b);
1242 return 0;
1243 }
1244
1245 bool hidden_or_backup_file(const char *filename) {
1246 assert(filename);
1247
1248 if (filename[0] == '.' ||
1249 STR_IN_SET(filename,
1250 "lost+found",
1251 "aquota.user",
1252 "aquota.group") ||
1253 endswith(filename, "~"))
1254 return true;
1255
1256 const char *dot = strrchr(filename, '.');
1257 if (!dot)
1258 return false;
1259
1260 /* Please, let's not add more entries to the list below. If external projects think it's a good idea
1261 * to come up with always new suffixes and that everybody else should just adjust to that, then it
1262 * really should be on them. Hence, in future, let's not add any more entries. Instead, let's ask
1263 * those packages to instead adopt one of the generic suffixes/prefixes for hidden files or backups,
1264 * possibly augmented with an additional string. Specifically: there's now:
1265 *
1266 * The generic suffixes "~" and ".bak" for backup files
1267 * The generic prefix "." for hidden files
1268 *
1269 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old",
1270 * ".foopkg-dist" or so registered, let's refuse that and ask them to use ".foopkg.new",
1271 * ".foopkg.old" or ".foopkg~" instead.
1272 */
1273
1274 return STR_IN_SET(dot + 1,
1275 "rpmnew",
1276 "rpmsave",
1277 "rpmorig",
1278 "dpkg-old",
1279 "dpkg-new",
1280 "dpkg-tmp",
1281 "dpkg-dist",
1282 "dpkg-bak",
1283 "dpkg-backup",
1284 "dpkg-remove",
1285 "ucf-new",
1286 "ucf-old",
1287 "ucf-dist",
1288 "swp",
1289 "bak",
1290 "old",
1291 "new");
1292 }
1293
1294 bool is_device_path(const char *path) {
1295
1296 /* Returns true for paths that likely refer to a device, either by path in sysfs or to something in
1297 * /dev. This accepts any path that starts with /dev/ or /sys/ and has something after that prefix.
1298 * It does not actually resolve the path.
1299 *
1300 * Examples:
1301 * /dev/sda, /dev/sda/foo, /sys/class, /dev/.., /sys/.., /./dev/foo → yes.
1302 * /../dev/sda, /dev, /sys, /usr/path, /usr/../dev/sda → no.
1303 */
1304
1305 const char *p = PATH_STARTSWITH_SET(ASSERT_PTR(path), "/dev/", "/sys/");
1306 return !isempty(p);
1307 }
1308
1309 bool valid_device_node_path(const char *path) {
1310
1311 /* Some superficial checks whether the specified path is a valid device node path, all without
1312 * looking at the actual device node. */
1313
1314 if (!PATH_STARTSWITH_SET(path, "/dev/", "/run/systemd/inaccessible/"))
1315 return false;
1316
1317 if (endswith(path, "/")) /* can't be a device node if it ends in a slash */
1318 return false;
1319
1320 return path_is_normalized(path);
1321 }
1322
1323 bool valid_device_allow_pattern(const char *path) {
1324 assert(path);
1325
1326 /* Like valid_device_node_path(), but also allows full-subsystem expressions like those accepted by
1327 * DeviceAllow= and DeviceDeny=. */
1328
1329 if (STARTSWITH_SET(path, "block-", "char-"))
1330 return true;
1331
1332 return valid_device_node_path(path);
1333 }
1334
1335 bool dot_or_dot_dot(const char *path) {
1336 if (!path)
1337 return false;
1338 if (path[0] != '.')
1339 return false;
1340 if (path[1] == 0)
1341 return true;
1342 if (path[1] != '.')
1343 return false;
1344
1345 return path[2] == 0;
1346 }
1347
1348 bool path_implies_directory(const char *path) {
1349
1350 /* Sometimes, if we look at a path we already know it must refer to a directory, because it is
1351 * suffixed with a slash, or its last component is "." or ".." */
1352
1353 if (!path)
1354 return false;
1355
1356 if (dot_or_dot_dot(path))
1357 return true;
1358
1359 return ENDSWITH_SET(path, "/", "/.", "/..");
1360 }
1361
1362 bool empty_or_root(const char *path) {
1363
1364 /* For operations relative to some root directory, returns true if the specified root directory is
1365 * redundant, i.e. either / or NULL or the empty string or any equivalent. */
1366
1367 if (isempty(path))
1368 return true;
1369
1370 return path_equal(path, "/");
1371 }
1372
1373 bool path_strv_contains(char * const *l, const char *path) {
1374 assert(path);
1375
1376 STRV_FOREACH(i, l)
1377 if (path_equal(*i, path))
1378 return true;
1379
1380 return false;
1381 }
1382
1383 bool prefixed_path_strv_contains(char * const *l, const char *path) {
1384 assert(path);
1385
1386 STRV_FOREACH(i, l) {
1387 const char *j = *i;
1388
1389 if (*j == '-')
1390 j++;
1391 if (*j == '+')
1392 j++;
1393
1394 if (path_equal(j, path))
1395 return true;
1396 }
1397
1398 return false;
1399 }
1400
1401 int path_glob_can_match(const char *pattern, const char *prefix, char **ret) {
1402 assert(pattern);
1403 assert(prefix);
1404
1405 for (const char *a = pattern, *b = prefix;;) {
1406 _cleanup_free_ char *g = NULL, *h = NULL;
1407 const char *p, *q;
1408 int r, s;
1409
1410 r = path_find_first_component(&a, /* accept_dot_dot = */ false, &p);
1411 if (r < 0)
1412 return r;
1413
1414 s = path_find_first_component(&b, /* accept_dot_dot = */ false, &q);
1415 if (s < 0)
1416 return s;
1417
1418 if (s == 0) {
1419 /* The pattern matches the prefix. */
1420 if (ret) {
1421 char *t;
1422
1423 t = path_join(prefix, p);
1424 if (!t)
1425 return -ENOMEM;
1426
1427 *ret = t;
1428 }
1429 return true;
1430 }
1431
1432 if (r == 0)
1433 break;
1434
1435 if (r == s && strneq(p, q, r))
1436 continue; /* common component. Check next. */
1437
1438 g = strndup(p, r);
1439 if (!g)
1440 return -ENOMEM;
1441
1442 if (!string_is_glob(g))
1443 break;
1444
1445 /* We found a glob component. Check if the glob pattern matches the prefix component. */
1446
1447 h = strndup(q, s);
1448 if (!h)
1449 return -ENOMEM;
1450
1451 r = fnmatch(g, h, 0);
1452 if (r == FNM_NOMATCH)
1453 break;
1454 if (r != 0) /* Failure to process pattern? */
1455 return -EINVAL;
1456 }
1457
1458 /* The pattern does not match the prefix. */
1459 if (ret)
1460 *ret = NULL;
1461 return false;
1462 }
1463
1464 const char* default_PATH(void) {
1465 #if HAVE_SPLIT_BIN
1466 static int split = -1;
1467 int r;
1468
1469 /* Check whether /usr/sbin is not a symlink and return the appropriate $PATH.
1470 * On error fall back to the safe value with both directories as configured… */
1471
1472 if (split < 0)
1473 STRV_FOREACH_PAIR(bin, sbin, STRV_MAKE("/usr/bin", "/usr/sbin",
1474 "/usr/local/bin", "/usr/local/sbin")) {
1475 r = inode_same(*bin, *sbin, AT_NO_AUTOMOUNT);
1476 if (r > 0 || r == -ENOENT)
1477 continue;
1478 if (r < 0)
1479 log_debug_errno(r, "Failed to compare \"%s\" and \"%s\", using compat $PATH: %m",
1480 *bin, *sbin);
1481 split = true;
1482 break;
1483 }
1484 if (split < 0)
1485 split = false;
1486 if (split)
1487 return DEFAULT_PATH_WITH_SBIN;
1488 #endif
1489 return DEFAULT_PATH_WITHOUT_SBIN;
1490 }