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