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