Debian Codegraph @

src/basic/path-util.c

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