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