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