]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/path-util.c
hexdecoct: make unbase64mem and unhexmem always use SIZE_MAX
[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 char* path_extend_internal(char **x, ...) {
529 size_t sz, old_sz;
530 char *q, *nx;
531 const char *p;
532 va_list ap;
533 bool slash;
534
535 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings
536 * end/begin already with one so that it is unnecessary. Note that slashes which are already
537 * duplicate won't be removed. The string returned is hence always equal to or longer than the sum of
538 * the lengths of the individual strings.
539 *
540 * The first argument may be an already allocated string that is extended via realloc() if
541 * non-NULL. path_extend() and path_join() are macro wrappers around this function, making use of the
542 * first parameter to distinguish the two operations.
543 *
544 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of
545 * which some are optional.
546 *
547 * Examples:
548 *
549 * path_join("foo", "bar") → "foo/bar"
550 * path_join("foo/", "bar") → "foo/bar"
551 * path_join("", "foo", "", "bar", "") → "foo/bar" */
552
553 sz = old_sz = x ? strlen_ptr(*x) : 0;
554 va_start(ap, x);
555 while ((p = va_arg(ap, char*)) != POINTER_MAX) {
556 size_t add;
557
558 if (isempty(p))
559 continue;
560
561 add = 1 + strlen(p);
562 if (sz > SIZE_MAX - add) { /* overflow check */
563 va_end(ap);
564 return NULL;
565 }
566
567 sz += add;
568 }
569 va_end(ap);
570
571 nx = realloc(x ? *x : NULL, GREEDY_ALLOC_ROUND_UP(sz+1));
572 if (!nx)
573 return NULL;
574 if (x)
575 *x = nx;
576
577 if (old_sz > 0)
578 slash = nx[old_sz-1] == '/';
579 else {
580 nx[old_sz] = 0;
581 slash = true; /* no need to generate a slash anymore */
582 }
583
584 q = nx + old_sz;
585
586 va_start(ap, x);
587 while ((p = va_arg(ap, char*)) != POINTER_MAX) {
588 if (isempty(p))
589 continue;
590
591 if (!slash && p[0] != '/')
592 *(q++) = '/';
593
594 q = stpcpy(q, p);
595 slash = endswith(p, "/");
596 }
597 va_end(ap);
598
599 return nx;
600 }
601
602 static int check_x_access(const char *path, int *ret_fd) {
603 _cleanup_close_ int fd = -EBADF;
604 int r;
605
606 /* We need to use O_PATH because there may be executables for which we have only exec
607 * permissions, but not read (usually suid executables). */
608 fd = open(path, O_PATH|O_CLOEXEC);
609 if (fd < 0)
610 return -errno;
611
612 r = fd_verify_regular(fd);
613 if (r < 0)
614 return r;
615
616 r = access_fd(fd, X_OK);
617 if (r == -ENOSYS) {
618 /* /proc is not mounted. Fallback to access(). */
619 if (access(path, X_OK) < 0)
620 return -errno;
621 } else if (r < 0)
622 return r;
623
624 if (ret_fd)
625 *ret_fd = TAKE_FD(fd);
626
627 return 0;
628 }
629
630 static int find_executable_impl(const char *name, const char *root, char **ret_filename, int *ret_fd) {
631 _cleanup_close_ int fd = -EBADF;
632 _cleanup_free_ char *path_name = NULL;
633 int r;
634
635 assert(name);
636
637 /* Function chase() is invoked only when root is not NULL, as using it regardless of
638 * root value would alter the behavior of existing callers for example: /bin/sleep would become
639 * /usr/bin/sleep when find_executables is called. Hence, this function should be invoked when
640 * needed to avoid unforeseen regression or other complicated changes. */
641 if (root) {
642 /* prefix root to name in case full paths are not specified */
643 r = chase(name, root, CHASE_PREFIX_ROOT, &path_name, /* ret_fd= */ NULL);
644 if (r < 0)
645 return r;
646
647 name = path_name;
648 }
649
650 r = check_x_access(name, ret_fd ? &fd : NULL);
651 if (r < 0)
652 return r;
653
654 if (ret_filename) {
655 r = path_make_absolute_cwd(name, ret_filename);
656 if (r < 0)
657 return r;
658 }
659
660 if (ret_fd)
661 *ret_fd = TAKE_FD(fd);
662
663 return 0;
664 }
665
666 int find_executable_full(
667 const char *name,
668 const char *root,
669 char **exec_search_path,
670 bool use_path_envvar,
671 char **ret_filename,
672 int *ret_fd) {
673
674 int last_error = -ENOENT, r = 0;
675 const char *p = NULL;
676
677 assert(name);
678
679 if (is_path(name))
680 return find_executable_impl(name, root, ret_filename, ret_fd);
681
682 if (use_path_envvar)
683 /* Plain getenv, not secure_getenv, because we want to actually allow the user to pick the
684 * binary. */
685 p = getenv("PATH");
686 if (!p)
687 p = DEFAULT_PATH;
688
689 if (exec_search_path) {
690 STRV_FOREACH(element, exec_search_path) {
691 _cleanup_free_ char *full_path = NULL;
692
693 if (!path_is_absolute(*element))
694 continue;
695
696 full_path = path_join(*element, name);
697 if (!full_path)
698 return -ENOMEM;
699
700 r = find_executable_impl(full_path, root, ret_filename, ret_fd);
701 if (r < 0) {
702 if (r != -EACCES)
703 last_error = r;
704 continue;
705 }
706 return 0;
707 }
708 return last_error;
709 }
710
711 /* Resolve a single-component name to a full path */
712 for (;;) {
713 _cleanup_free_ char *element = NULL;
714
715 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
716 if (r < 0)
717 return r;
718 if (r == 0)
719 break;
720
721 if (!path_is_absolute(element))
722 continue;
723
724 if (!path_extend(&element, name))
725 return -ENOMEM;
726
727 r = find_executable_impl(element, root, ret_filename, ret_fd);
728 if (r < 0) {
729 /* PATH entries which we don't have access to are ignored, as per tradition. */
730 if (r != -EACCES)
731 last_error = r;
732 continue;
733 }
734
735 /* Found it! */
736 return 0;
737 }
738
739 return last_error;
740 }
741
742 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
743 bool changed = false, originally_unset;
744
745 assert(timestamp);
746
747 if (!paths)
748 return false;
749
750 originally_unset = *timestamp == 0;
751
752 STRV_FOREACH(i, paths) {
753 struct stat stats;
754 usec_t u;
755
756 if (stat(*i, &stats) < 0)
757 continue;
758
759 u = timespec_load(&stats.st_mtim);
760
761 /* check first */
762 if (*timestamp >= u)
763 continue;
764
765 log_debug(originally_unset ? "Loaded timestamp for '%s'." : "Timestamp of '%s' changed.", *i);
766
767 /* update timestamp */
768 if (update) {
769 *timestamp = u;
770 changed = true;
771 } else
772 return true;
773 }
774
775 return changed;
776 }
777
778 static int executable_is_good(const char *executable) {
779 _cleanup_free_ char *p = NULL, *d = NULL;
780 int r;
781
782 r = find_executable(executable, &p);
783 if (r == -ENOENT)
784 return 0;
785 if (r < 0)
786 return r;
787
788 /* An fsck that is linked to /bin/true is a non-existent fsck */
789
790 r = readlink_malloc(p, &d);
791 if (r == -EINVAL) /* not a symlink */
792 return 1;
793 if (r < 0)
794 return r;
795
796 return !PATH_IN_SET(d, "true"
797 "/bin/true",
798 "/usr/bin/true",
799 "/dev/null");
800 }
801
802 int fsck_exists(void) {
803 return executable_is_good("fsck");
804 }
805
806 int fsck_exists_for_fstype(const char *fstype) {
807 const char *checker;
808 int r;
809
810 assert(fstype);
811
812 if (streq(fstype, "auto"))
813 return -EINVAL;
814
815 r = fsck_exists();
816 if (r <= 0)
817 return r;
818
819 checker = strjoina("fsck.", fstype);
820 return executable_is_good(checker);
821 }
822
823 static const char* skip_slash_or_dot(const char *p) {
824 for (; !isempty(p); p++) {
825 if (*p == '/')
826 continue;
827 if (startswith(p, "./")) {
828 p++;
829 continue;
830 }
831 break;
832 }
833 return p;
834 }
835
836 int path_find_first_component(const char **p, bool accept_dot_dot, const char **ret) {
837 const char *q, *first, *end_first, *next;
838 size_t len;
839
840 assert(p);
841
842 /* When a path is input, then returns the pointer to the first component and its length, and
843 * move the input pointer to the next component or nul. This skips both over any '/'
844 * immediately *before* and *after* the first component before returning.
845 *
846 * Examples
847 * Input: p: "//.//aaa///bbbbb/cc"
848 * Output: p: "bbbbb///cc"
849 * ret: "aaa///bbbbb/cc"
850 * return value: 3 (== strlen("aaa"))
851 *
852 * Input: p: "aaa//"
853 * Output: p: (pointer to NUL)
854 * ret: "aaa//"
855 * return value: 3 (== strlen("aaa"))
856 *
857 * Input: p: "/", ".", ""
858 * Output: p: (pointer to NUL)
859 * ret: NULL
860 * return value: 0
861 *
862 * Input: p: NULL
863 * Output: p: NULL
864 * ret: NULL
865 * return value: 0
866 *
867 * Input: p: "(too long component)"
868 * Output: return value: -EINVAL
869 *
870 * (when accept_dot_dot is false)
871 * Input: p: "//..//aaa///bbbbb/cc"
872 * Output: return value: -EINVAL
873 */
874
875 q = *p;
876
877 first = skip_slash_or_dot(q);
878 if (isempty(first)) {
879 *p = first;
880 if (ret)
881 *ret = NULL;
882 return 0;
883 }
884 if (streq(first, ".")) {
885 *p = first + 1;
886 if (ret)
887 *ret = NULL;
888 return 0;
889 }
890
891 end_first = strchrnul(first, '/');
892 len = end_first - first;
893
894 if (len > NAME_MAX)
895 return -EINVAL;
896 if (!accept_dot_dot && len == 2 && first[0] == '.' && first[1] == '.')
897 return -EINVAL;
898
899 next = skip_slash_or_dot(end_first);
900
901 *p = next + streq(next, ".");
902 if (ret)
903 *ret = first;
904 return len;
905 }
906
907 static const char* skip_slash_or_dot_backward(const char *path, const char *q) {
908 assert(path);
909 assert(!q || q >= path);
910
911 for (; q; q = PTR_SUB1(q, path)) {
912 if (*q == '/')
913 continue;
914 if (q > path && strneq(q - 1, "/.", 2))
915 continue;
916 if (q == path && *q == '.')
917 continue;
918 break;
919 }
920 return q;
921 }
922
923 int path_find_last_component(const char *path, bool accept_dot_dot, const char **next, const char **ret) {
924 const char *q, *last_end, *last_begin;
925 size_t len;
926
927 /* Similar to path_find_first_component(), but search components from the end.
928 *
929 * Examples
930 * Input: path: "//.//aaa///bbbbb/cc//././"
931 * next: NULL
932 * Output: next: "/cc//././"
933 * ret: "cc//././"
934 * return value: 2 (== strlen("cc"))
935 *
936 * Input: path: "//.//aaa///bbbbb/cc//././"
937 * next: "/cc//././"
938 * Output: next: "///bbbbb/cc//././"
939 * ret: "bbbbb/cc//././"
940 * return value: 5 (== strlen("bbbbb"))
941 *
942 * Input: path: "//.//aaa///bbbbb/cc//././"
943 * next: "///bbbbb/cc//././"
944 * Output: next: "//.//aaa///bbbbb/cc//././" (next == path)
945 * ret: "aaa///bbbbb/cc//././"
946 * return value: 3 (== strlen("aaa"))
947 *
948 * Input: path: "/", ".", "", or NULL
949 * Output: next: equivalent to path
950 * ret: NULL
951 * return value: 0
952 *
953 * Input: path: "(too long component)"
954 * Output: return value: -EINVAL
955 *
956 * (when accept_dot_dot is false)
957 * Input: path: "//..//aaa///bbbbb/cc/..//"
958 * Output: return value: -EINVAL
959 */
960
961 if (isempty(path)) {
962 if (next)
963 *next = path;
964 if (ret)
965 *ret = NULL;
966 return 0;
967 }
968
969 if (next && *next) {
970 if (*next < path || *next > path + strlen(path))
971 return -EINVAL;
972 if (*next == path) {
973 if (ret)
974 *ret = NULL;
975 return 0;
976 }
977 if (!IN_SET(**next, '\0', '/'))
978 return -EINVAL;
979 q = *next - 1;
980 } else
981 q = path + strlen(path) - 1;
982
983 q = skip_slash_or_dot_backward(path, q);
984 if (!q || /* the root directory */
985 (q == path && *q == '.')) { /* path is "." or "./" */
986 if (next)
987 *next = path;
988 if (ret)
989 *ret = NULL;
990 return 0;
991 }
992
993 last_end = q + 1;
994
995 while (q && *q != '/')
996 q = PTR_SUB1(q, path);
997
998 last_begin = q ? q + 1 : path;
999 len = last_end - last_begin;
1000
1001 if (len > NAME_MAX)
1002 return -EINVAL;
1003 if (!accept_dot_dot && len == 2 && strneq(last_begin, "..", 2))
1004 return -EINVAL;
1005
1006 if (next) {
1007 q = skip_slash_or_dot_backward(path, q);
1008 *next = q ? q + 1 : path;
1009 }
1010
1011 if (ret)
1012 *ret = last_begin;
1013 return len;
1014 }
1015
1016 const char* last_path_component(const char *path) {
1017
1018 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
1019 *
1020 * a/b/c → c
1021 * a/b/c/ → c/
1022 * x → x
1023 * x/ → x/
1024 * /y → y
1025 * /y/ → y/
1026 * / → /
1027 * // → /
1028 * /foo/a → a
1029 * /foo/a/ → a/
1030 *
1031 * Also, the empty string is mapped to itself.
1032 *
1033 * This is different than basename(), which returns "" when a trailing slash is present.
1034 *
1035 * This always succeeds (except if you pass NULL in which case it returns NULL, too).
1036 */
1037
1038 unsigned l, k;
1039
1040 if (!path)
1041 return NULL;
1042
1043 l = k = strlen(path);
1044 if (l == 0) /* special case — an empty string */
1045 return path;
1046
1047 while (k > 0 && path[k-1] == '/')
1048 k--;
1049
1050 if (k == 0) /* the root directory */
1051 return path + l - 1;
1052
1053 while (k > 0 && path[k-1] != '/')
1054 k--;
1055
1056 return path + k;
1057 }
1058
1059 int path_extract_filename(const char *path, char **ret) {
1060 _cleanup_free_ char *a = NULL;
1061 const char *c, *next = NULL;
1062 int r;
1063
1064 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
1065 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing
1066 * slashes. Returns:
1067 *
1068 * -EINVAL → if the path is not valid
1069 * -EADDRNOTAVAIL → if only a directory was specified, but no filename, i.e. the root dir
1070 * itself or "." is specified
1071 * -ENOMEM → no memory
1072 *
1073 * Returns >= 0 on success. If the input path has a trailing slash, returns O_DIRECTORY, to
1074 * indicate the referenced file must be a directory.
1075 *
1076 * This function guarantees to return a fully valid filename, i.e. one that passes
1077 * filename_is_valid() – this means "." and ".." are not accepted. */
1078
1079 if (!path_is_valid(path))
1080 return -EINVAL;
1081
1082 r = path_find_last_component(path, false, &next, &c);
1083 if (r < 0)
1084 return r;
1085 if (r == 0) /* root directory */
1086 return -EADDRNOTAVAIL;
1087
1088 a = strndup(c, r);
1089 if (!a)
1090 return -ENOMEM;
1091
1092 *ret = TAKE_PTR(a);
1093 return strlen(c) > (size_t) r ? O_DIRECTORY : 0;
1094 }
1095
1096 int path_extract_directory(const char *path, char **ret) {
1097 _cleanup_free_ char *a = NULL;
1098 const char *c, *next = NULL;
1099 int r;
1100
1101 /* The inverse of path_extract_filename(), i.e. returns the directory path prefix. Returns:
1102 *
1103 * -EINVAL → if the path is not valid
1104 * -EDESTADDRREQ → if no directory was specified in the passed in path, i.e. only a filename was passed
1105 * -EADDRNOTAVAIL → if the passed in parameter had no filename but did have a directory, i.e.
1106 * the root dir itself or "." was specified
1107 * -ENOMEM → no memory (surprise!)
1108 *
1109 * This function guarantees to return a fully valid path, i.e. one that passes path_is_valid().
1110 */
1111
1112 r = path_find_last_component(path, false, &next, &c);
1113 if (r < 0)
1114 return r;
1115 if (r == 0) /* empty or root */
1116 return isempty(path) ? -EINVAL : -EADDRNOTAVAIL;
1117 if (next == path) {
1118 if (*path != '/') /* filename only */
1119 return -EDESTADDRREQ;
1120
1121 a = strdup("/");
1122 if (!a)
1123 return -ENOMEM;
1124 *ret = TAKE_PTR(a);
1125 return 0;
1126 }
1127
1128 a = strndup(path, next - path);
1129 if (!a)
1130 return -ENOMEM;
1131
1132 path_simplify(a);
1133
1134 if (!path_is_valid(a))
1135 return -EINVAL;
1136
1137 if (ret)
1138 *ret = TAKE_PTR(a);
1139
1140 return 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 "rpmnew",
1267 "rpmsave",
1268 "rpmorig",
1269 "dpkg-old",
1270 "dpkg-new",
1271 "dpkg-tmp",
1272 "dpkg-dist",
1273 "dpkg-bak",
1274 "dpkg-backup",
1275 "dpkg-remove",
1276 "ucf-new",
1277 "ucf-old",
1278 "ucf-dist",
1279 "swp",
1280 "bak",
1281 "old",
1282 "new");
1283 }
1284
1285 bool is_device_path(const char *path) {
1286
1287 /* Returns true for paths that likely refer to a device, either by path in sysfs or to something in
1288 * /dev. This accepts any path that starts with /dev/ or /sys/ and has something after that prefix.
1289 * It does not actually resolve the path.
1290 *
1291 * Examples:
1292 * /dev/sda, /dev/sda/foo, /sys/class, /dev/.., /sys/.., /./dev/foo → yes.
1293 * /../dev/sda, /dev, /sys, /usr/path, /usr/../dev/sda → no.
1294 */
1295
1296 const char *p = PATH_STARTSWITH_SET(ASSERT_PTR(path), "/dev/", "/sys/");
1297 return !isempty(p);
1298 }
1299
1300 bool valid_device_node_path(const char *path) {
1301
1302 /* Some superficial checks whether the specified path is a valid device node path, all without
1303 * looking at the actual device node. */
1304
1305 if (!PATH_STARTSWITH_SET(path, "/dev/", "/run/systemd/inaccessible/"))
1306 return false;
1307
1308 if (endswith(path, "/")) /* can't be a device node if it ends in a slash */
1309 return false;
1310
1311 return path_is_normalized(path);
1312 }
1313
1314 bool valid_device_allow_pattern(const char *path) {
1315 assert(path);
1316
1317 /* Like valid_device_node_path(), but also allows full-subsystem expressions like those accepted by
1318 * DeviceAllow= and DeviceDeny=. */
1319
1320 if (STARTSWITH_SET(path, "block-", "char-"))
1321 return true;
1322
1323 return valid_device_node_path(path);
1324 }
1325
1326 bool dot_or_dot_dot(const char *path) {
1327 if (!path)
1328 return false;
1329 if (path[0] != '.')
1330 return false;
1331 if (path[1] == 0)
1332 return true;
1333 if (path[1] != '.')
1334 return false;
1335
1336 return path[2] == 0;
1337 }
1338
1339 bool empty_or_root(const char *path) {
1340
1341 /* For operations relative to some root directory, returns true if the specified root directory is
1342 * redundant, i.e. either / or NULL or the empty string or any equivalent. */
1343
1344 if (isempty(path))
1345 return true;
1346
1347 return path_equal(path, "/");
1348 }
1349
1350 bool path_strv_contains(char **l, const char *path) {
1351 STRV_FOREACH(i, l)
1352 if (path_equal(*i, path))
1353 return true;
1354
1355 return false;
1356 }
1357
1358 bool prefixed_path_strv_contains(char **l, const char *path) {
1359 STRV_FOREACH(i, l) {
1360 const char *j = *i;
1361
1362 if (*j == '-')
1363 j++;
1364 if (*j == '+')
1365 j++;
1366 if (path_equal(j, path))
1367 return true;
1368 }
1369
1370 return false;
1371 }
1372
1373 int path_glob_can_match(const char *pattern, const char *prefix, char **ret) {
1374 assert(pattern);
1375 assert(prefix);
1376
1377 for (const char *a = pattern, *b = prefix;;) {
1378 _cleanup_free_ char *g = NULL, *h = NULL;
1379 const char *p, *q;
1380 int r, s;
1381
1382 r = path_find_first_component(&a, /* accept_dot_dot = */ false, &p);
1383 if (r < 0)
1384 return r;
1385
1386 s = path_find_first_component(&b, /* accept_dot_dot = */ false, &q);
1387 if (s < 0)
1388 return s;
1389
1390 if (s == 0) {
1391 /* The pattern matches the prefix. */
1392 if (ret) {
1393 char *t;
1394
1395 t = path_join(prefix, p);
1396 if (!t)
1397 return -ENOMEM;
1398
1399 *ret = t;
1400 }
1401 return true;
1402 }
1403
1404 if (r == 0)
1405 break;
1406
1407 if (r == s && strneq(p, q, r))
1408 continue; /* common component. Check next. */
1409
1410 g = strndup(p, r);
1411 if (!g)
1412 return -ENOMEM;
1413
1414 if (!string_is_glob(g))
1415 break;
1416
1417 /* We found a glob component. Check if the glob pattern matches the prefix component. */
1418
1419 h = strndup(q, s);
1420 if (!h)
1421 return -ENOMEM;
1422
1423 r = fnmatch(g, h, 0);
1424 if (r == FNM_NOMATCH)
1425 break;
1426 if (r != 0) /* Failure to process pattern? */
1427 return -EINVAL;
1428 }
1429
1430 /* The pattern does not match the prefix. */
1431 if (ret)
1432 *ret = NULL;
1433 return false;
1434 }