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