]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/path-util.c
Merge pull request #20166 from poettering/fsync-more
[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 int find_executable_full(const char *name, bool use_path_envvar, char **ret_filename, int *ret_fd) {
643 int last_error, r;
644 const char *p = NULL;
645
646 assert(name);
647
648 if (is_path(name)) {
649 _cleanup_close_ int fd = -1;
650
651 r = check_x_access(name, ret_fd ? &fd : NULL);
652 if (r < 0)
653 return r;
654
655 if (ret_filename) {
656 r = path_make_absolute_cwd(name, ret_filename);
657 if (r < 0)
658 return r;
659 }
660
661 if (ret_fd)
662 *ret_fd = TAKE_FD(fd);
663
664 return 0;
665 }
666
667 if (use_path_envvar)
668 /* Plain getenv, not secure_getenv, because we want to actually allow the user to pick the
669 * binary. */
670 p = getenv("PATH");
671 if (!p)
672 p = DEFAULT_PATH;
673
674 last_error = -ENOENT;
675
676 /* Resolve a single-component name to a full path */
677 for (;;) {
678 _cleanup_free_ char *element = NULL;
679 _cleanup_close_ int fd = -1;
680
681 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
682 if (r < 0)
683 return r;
684 if (r == 0)
685 break;
686
687 if (!path_is_absolute(element))
688 continue;
689
690 if (!path_extend(&element, name))
691 return -ENOMEM;
692
693 r = check_x_access(element, ret_fd ? &fd : NULL);
694 if (r < 0) {
695 /* PATH entries which we don't have access to are ignored, as per tradition. */
696 if (r != -EACCES)
697 last_error = r;
698 continue;
699 }
700
701 /* Found it! */
702 if (ret_filename)
703 *ret_filename = path_simplify(TAKE_PTR(element));
704 if (ret_fd)
705 *ret_fd = TAKE_FD(fd);
706
707 return 0;
708 }
709
710 return last_error;
711 }
712
713 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
714 bool changed = false, originally_unset;
715 const char* const* i;
716
717 assert(timestamp);
718
719 if (!paths)
720 return false;
721
722 originally_unset = *timestamp == 0;
723
724 STRV_FOREACH(i, paths) {
725 struct stat stats;
726 usec_t u;
727
728 if (stat(*i, &stats) < 0)
729 continue;
730
731 u = timespec_load(&stats.st_mtim);
732
733 /* check first */
734 if (*timestamp >= u)
735 continue;
736
737 log_debug(originally_unset ? "Loaded timestamp for '%s'." : "Timestamp of '%s' changed.", *i);
738
739 /* update timestamp */
740 if (update) {
741 *timestamp = u;
742 changed = true;
743 } else
744 return true;
745 }
746
747 return changed;
748 }
749
750 static int executable_is_good(const char *executable) {
751 _cleanup_free_ char *p = NULL, *d = NULL;
752 int r;
753
754 r = find_executable(executable, &p);
755 if (r == -ENOENT)
756 return 0;
757 if (r < 0)
758 return r;
759
760 /* An fsck that is linked to /bin/true is a non-existent fsck */
761
762 r = readlink_malloc(p, &d);
763 if (r == -EINVAL) /* not a symlink */
764 return 1;
765 if (r < 0)
766 return r;
767
768 return !PATH_IN_SET(d, "true"
769 "/bin/true",
770 "/usr/bin/true",
771 "/dev/null");
772 }
773
774 int fsck_exists(const char *fstype) {
775 const char *checker;
776
777 assert(fstype);
778
779 if (streq(fstype, "auto"))
780 return -EINVAL;
781
782 checker = strjoina("fsck.", fstype);
783 return executable_is_good(checker);
784 }
785
786 char* dirname_malloc(const char *path) {
787 char *d, *dir, *dir2;
788
789 assert(path);
790
791 d = strdup(path);
792 if (!d)
793 return NULL;
794
795 dir = dirname(d);
796 assert(dir);
797
798 if (dir == d)
799 return d;
800
801 dir2 = strdup(dir);
802 free(d);
803
804 return dir2;
805 }
806
807 static const char *skip_slash_or_dot(const char *p) {
808 for (; !isempty(p); p++) {
809 if (*p == '/')
810 continue;
811 if (startswith(p, "./")) {
812 p++;
813 continue;
814 }
815 break;
816 }
817 return p;
818 }
819
820 int path_find_first_component(const char **p, bool accept_dot_dot, const char **ret) {
821 const char *q, *first, *end_first, *next;
822 size_t len;
823
824 assert(p);
825
826 /* When a path is input, then returns the pointer to the first component and its length, and
827 * move the input pointer to the next component or nul. This skips both over any '/'
828 * immediately *before* and *after* the first component before returning.
829 *
830 * Examples
831 * Input: p: "//.//aaa///bbbbb/cc"
832 * Output: p: "bbbbb///cc"
833 * ret: "aaa///bbbbb/cc"
834 * return value: 3 (== strlen("aaa"))
835 *
836 * Input: p: "aaa//"
837 * Output: p: (pointer to NUL)
838 * ret: "aaa//"
839 * return value: 3 (== strlen("aaa"))
840 *
841 * Input: p: "/", ".", ""
842 * Output: p: (pointer to NUL)
843 * ret: NULL
844 * return value: 0
845 *
846 * Input: p: NULL
847 * Output: p: NULL
848 * ret: NULL
849 * return value: 0
850 *
851 * Input: p: "(too long component)"
852 * Output: return value: -EINVAL
853 *
854 * (when accept_dot_dot is false)
855 * Input: p: "//..//aaa///bbbbb/cc"
856 * Output: return value: -EINVAL
857 */
858
859 q = *p;
860
861 first = skip_slash_or_dot(q);
862 if (isempty(first)) {
863 *p = first;
864 if (ret)
865 *ret = NULL;
866 return 0;
867 }
868 if (streq(first, ".")) {
869 *p = first + 1;
870 if (ret)
871 *ret = NULL;
872 return 0;
873 }
874
875 end_first = strchrnul(first, '/');
876 len = end_first - first;
877
878 if (len > NAME_MAX)
879 return -EINVAL;
880 if (!accept_dot_dot && len == 2 && first[0] == '.' && first[1] == '.')
881 return -EINVAL;
882
883 next = skip_slash_or_dot(end_first);
884
885 *p = next + streq(next, ".");
886 if (ret)
887 *ret = first;
888 return len;
889 }
890
891 static const char *skip_slash_or_dot_backward(const char *path, const char *q) {
892 assert(path);
893
894 for (; q >= path; q--) {
895 if (*q == '/')
896 continue;
897 if (q > path && strneq(q - 1, "/.", 2))
898 continue;
899 break;
900 }
901 return q;
902 }
903
904 int path_find_last_component(const char *path, bool accept_dot_dot, const char **next, const char **ret) {
905 const char *q, *last_end, *last_begin;
906 size_t len;
907
908 /* Similar to path_find_first_component(), but search components from the end.
909 *
910 * Examples
911 * Input: path: "//.//aaa///bbbbb/cc//././"
912 * next: NULL
913 * Output: next: "/cc//././"
914 * ret: "cc//././"
915 * return value: 2 (== strlen("cc"))
916 *
917 * Input: path: "//.//aaa///bbbbb/cc//././"
918 * next: "/cc//././"
919 * Output: next: "///bbbbb/cc//././"
920 * ret: "bbbbb/cc//././"
921 * return value: 5 (== strlen("bbbbb"))
922 *
923 * Input: path: "/", ".", "", or NULL
924 * Output: next: equivalent to path
925 * ret: NULL
926 * return value: 0
927 *
928 * Input: path: "(too long component)"
929 * Output: return value: -EINVAL
930 *
931 * (when accept_dot_dot is false)
932 * Input: path: "//..//aaa///bbbbb/cc/..//"
933 * Output: return value: -EINVAL
934 */
935
936 if (isempty(path)) {
937 if (next)
938 *next = path;
939 if (ret)
940 *ret = NULL;
941 return 0;
942 }
943
944 if (next && *next) {
945 if (*next < path || *next > path + strlen(path))
946 return -EINVAL;
947 if (*next == path) {
948 if (ret)
949 *ret = NULL;
950 return 0;
951 }
952 if (!IN_SET(**next, '\0', '/'))
953 return -EINVAL;
954 q = *next - 1;
955 } else
956 q = path + strlen(path) - 1;
957
958 q = skip_slash_or_dot_backward(path, q);
959 if ((q < path) || /* the root directory */
960 (q == path && *q == '.')) { /* path is "." or "./" */
961 if (next)
962 *next = path;
963 if (ret)
964 *ret = NULL;
965 return 0;
966 }
967
968 last_end = q + 1;
969
970 while (q >= path && *q != '/')
971 q--;
972
973 last_begin = q + 1;
974 len = last_end - last_begin;
975
976 if (len > NAME_MAX)
977 return -EINVAL;
978 if (!accept_dot_dot && len == 2 && strneq(last_begin, "..", 2))
979 return -EINVAL;
980
981 if (next) {
982 q = skip_slash_or_dot_backward(path, q);
983 if (q < path)
984 *next = path;
985 else
986 *next = q + 1;
987 }
988
989 if (ret)
990 *ret = last_begin;
991 return len;
992 }
993
994 const char *last_path_component(const char *path) {
995
996 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
997 *
998 * a/b/c → c
999 * a/b/c/ → c/
1000 * x → x
1001 * x/ → x/
1002 * /y → y
1003 * /y/ → y/
1004 * / → /
1005 * // → /
1006 * /foo/a → a
1007 * /foo/a/ → a/
1008 *
1009 * Also, the empty string is mapped to itself.
1010 *
1011 * This is different than basename(), which returns "" when a trailing slash is present.
1012 *
1013 * This always succeeds (except if you pass NULL in which case it returns NULL, too).
1014 */
1015
1016 unsigned l, k;
1017
1018 if (!path)
1019 return NULL;
1020
1021 l = k = strlen(path);
1022 if (l == 0) /* special case — an empty string */
1023 return path;
1024
1025 while (k > 0 && path[k-1] == '/')
1026 k--;
1027
1028 if (k == 0) /* the root directory */
1029 return path + l - 1;
1030
1031 while (k > 0 && path[k-1] != '/')
1032 k--;
1033
1034 return path + k;
1035 }
1036
1037 int path_extract_filename(const char *path, char **ret) {
1038 _cleanup_free_ char *a = NULL;
1039 const char *c, *next = NULL;
1040 int r;
1041
1042 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
1043 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing
1044 * slashes. Returns:
1045 *
1046 * -EINVAL → if the path is not valid
1047 * -EADDRNOTAVAIL → if only a directory was specified, but no filename, i.e. the root dir
1048 * itself or "." is specified
1049 * -ENOMEM → no memory
1050 *
1051 * Returns >= 0 on success. If the input path has a trailing slash, returns O_DIRECTORY, to
1052 * indicate the referenced file must be a directory.
1053 *
1054 * This function guarantees to return a fully valid filename, i.e. one that passes
1055 * filename_is_valid() – this means "." and ".." are not accepted. */
1056
1057 if (!path_is_valid(path))
1058 return -EINVAL;
1059
1060 r = path_find_last_component(path, false, &next, &c);
1061 if (r < 0)
1062 return r;
1063 if (r == 0) /* root directory */
1064 return -EADDRNOTAVAIL;
1065
1066 a = strndup(c, r);
1067 if (!a)
1068 return -ENOMEM;
1069
1070 *ret = TAKE_PTR(a);
1071 return strlen(c) > (size_t)r ? O_DIRECTORY : 0;
1072 }
1073
1074 int path_extract_directory(const char *path, char **ret) {
1075 _cleanup_free_ char *a = NULL;
1076 const char *c, *next = NULL;
1077 int r;
1078
1079 /* The inverse of path_extract_filename(), i.e. returns the directory path prefix. Returns:
1080 *
1081 * -EINVAL → if the path is not valid
1082 * -EDESTADDRREQ → if no directory was specified in the passed in path, i.e. only a filename was passed
1083 * -EADDRNOTAVAIL → if the passed in parameter had no filename but did have a directory, i.e.
1084 * the root dir itself or "." was specified
1085 * -ENOMEM → no memory (surprise!)
1086 *
1087 * This function guarantees to return a fully valid path, i.e. one that passes path_is_valid().
1088 */
1089
1090 r = path_find_last_component(path, false, &next, &c);
1091 if (r < 0)
1092 return r;
1093 if (r == 0) /* empty or root */
1094 return isempty(path) ? -EINVAL : -EADDRNOTAVAIL;
1095 if (next == path) {
1096 if (*path != '/') /* filename only */
1097 return -EDESTADDRREQ;
1098
1099 a = strdup("/");
1100 if (!a)
1101 return -ENOMEM;
1102 *ret = TAKE_PTR(a);
1103 return 0;
1104 }
1105
1106 a = strndup(path, next - path);
1107 if (!a)
1108 return -ENOMEM;
1109
1110 path_simplify(a);
1111
1112 if (!path_is_valid(a))
1113 return -EINVAL;
1114
1115 *ret = TAKE_PTR(a);
1116 return 0;
1117 }
1118
1119 bool filename_is_valid(const char *p) {
1120 const char *e;
1121
1122 if (isempty(p))
1123 return false;
1124
1125 if (dot_or_dot_dot(p))
1126 return false;
1127
1128 e = strchrnul(p, '/');
1129 if (*e != 0)
1130 return false;
1131
1132 if (e - p > NAME_MAX) /* NAME_MAX is counted *without* the trailing NUL byte */
1133 return false;
1134
1135 return true;
1136 }
1137
1138 bool path_is_valid_full(const char *p, bool accept_dot_dot) {
1139 if (isempty(p))
1140 return false;
1141
1142 for (const char *e = p;;) {
1143 int r;
1144
1145 r = path_find_first_component(&e, accept_dot_dot, NULL);
1146 if (r < 0)
1147 return false;
1148
1149 if (e - p >= PATH_MAX) /* Already reached the maximum length for a path? (PATH_MAX is counted
1150 * *with* the trailing NUL byte) */
1151 return false;
1152 if (*e == 0) /* End of string? Yay! */
1153 return true;
1154 }
1155 }
1156
1157 bool path_is_normalized(const char *p) {
1158 if (!path_is_safe(p))
1159 return false;
1160
1161 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
1162 return false;
1163
1164 if (strstr(p, "//"))
1165 return false;
1166
1167 return true;
1168 }
1169
1170 char *file_in_same_dir(const char *path, const char *filename) {
1171 char *e, *ret;
1172 size_t k;
1173
1174 assert(path);
1175 assert(filename);
1176
1177 /* This removes the last component of path and appends
1178 * filename, unless the latter is absolute anyway or the
1179 * former isn't */
1180
1181 if (path_is_absolute(filename))
1182 return strdup(filename);
1183
1184 e = strrchr(path, '/');
1185 if (!e)
1186 return strdup(filename);
1187
1188 k = strlen(filename);
1189 ret = new(char, (e + 1 - path) + k + 1);
1190 if (!ret)
1191 return NULL;
1192
1193 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
1194 return ret;
1195 }
1196
1197 bool hidden_or_backup_file(const char *filename) {
1198 const char *p;
1199
1200 assert(filename);
1201
1202 if (filename[0] == '.' ||
1203 streq(filename, "lost+found") ||
1204 streq(filename, "aquota.user") ||
1205 streq(filename, "aquota.group") ||
1206 endswith(filename, "~"))
1207 return true;
1208
1209 p = strrchr(filename, '.');
1210 if (!p)
1211 return false;
1212
1213 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
1214 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
1215 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
1216 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
1217 * string. Specifically: there's now:
1218 *
1219 * The generic suffixes "~" and ".bak" for backup files
1220 * The generic prefix "." for hidden files
1221 *
1222 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
1223 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
1224 */
1225
1226 return STR_IN_SET(p + 1,
1227 "rpmnew",
1228 "rpmsave",
1229 "rpmorig",
1230 "dpkg-old",
1231 "dpkg-new",
1232 "dpkg-tmp",
1233 "dpkg-dist",
1234 "dpkg-bak",
1235 "dpkg-backup",
1236 "dpkg-remove",
1237 "ucf-new",
1238 "ucf-old",
1239 "ucf-dist",
1240 "swp",
1241 "bak",
1242 "old",
1243 "new");
1244 }
1245
1246 bool is_device_path(const char *path) {
1247
1248 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
1249
1250 return PATH_STARTSWITH_SET(path, "/dev/", "/sys/");
1251 }
1252
1253 bool valid_device_node_path(const char *path) {
1254
1255 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
1256 * actual device node. */
1257
1258 if (!PATH_STARTSWITH_SET(path, "/dev/", "/run/systemd/inaccessible/"))
1259 return false;
1260
1261 if (endswith(path, "/")) /* can't be a device node if it ends in a slash */
1262 return false;
1263
1264 return path_is_normalized(path);
1265 }
1266
1267 bool valid_device_allow_pattern(const char *path) {
1268 assert(path);
1269
1270 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
1271 * accept it */
1272
1273 if (STARTSWITH_SET(path, "block-", "char-"))
1274 return true;
1275
1276 return valid_device_node_path(path);
1277 }
1278
1279 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
1280 const char *pattern;
1281 int r;
1282
1283 /* Try to guess if systemd installation is later than the specified version. This
1284 * is hacky and likely to yield false negatives, particularly if the installation
1285 * is non-standard. False positives should be relatively rare.
1286 */
1287
1288 NULSTR_FOREACH(pattern,
1289 /* /lib works for systems without usr-merge, and for systems with a sane
1290 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
1291 * for Gentoo which does a merge without making /lib a symlink.
1292 */
1293 "lib/systemd/libsystemd-shared-*.so\0"
1294 "lib64/systemd/libsystemd-shared-*.so\0"
1295 "usr/lib/systemd/libsystemd-shared-*.so\0"
1296 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
1297
1298 _cleanup_strv_free_ char **names = NULL;
1299 _cleanup_free_ char *path = NULL;
1300 char *c, **name;
1301
1302 path = path_join(root, pattern);
1303 if (!path)
1304 return -ENOMEM;
1305
1306 r = glob_extend(&names, path, 0);
1307 if (r == -ENOENT)
1308 continue;
1309 if (r < 0)
1310 return r;
1311
1312 assert_se(c = endswith(path, "*.so"));
1313 *c = '\0'; /* truncate the glob part */
1314
1315 STRV_FOREACH(name, names) {
1316 /* This is most likely to run only once, hence let's not optimize anything. */
1317 char *t, *t2;
1318 unsigned version;
1319
1320 t = startswith(*name, path);
1321 if (!t)
1322 continue;
1323
1324 t2 = endswith(t, ".so");
1325 if (!t2)
1326 continue;
1327
1328 t2[0] = '\0'; /* truncate the suffix */
1329
1330 r = safe_atou(t, &version);
1331 if (r < 0) {
1332 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
1333 continue;
1334 }
1335
1336 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1337 *name, version,
1338 version >= minimal_version ? "OK" : "too old");
1339 if (version >= minimal_version)
1340 return true;
1341 }
1342 }
1343
1344 return false;
1345 }
1346
1347 bool dot_or_dot_dot(const char *path) {
1348 if (!path)
1349 return false;
1350 if (path[0] != '.')
1351 return false;
1352 if (path[1] == 0)
1353 return true;
1354 if (path[1] != '.')
1355 return false;
1356
1357 return path[2] == 0;
1358 }
1359
1360 bool empty_or_root(const char *path) {
1361
1362 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1363 * i.e. either / or NULL or the empty string or any equivalent. */
1364
1365 if (isempty(path))
1366 return true;
1367
1368 return path_equal(path, "/");
1369 }
1370
1371 bool path_strv_contains(char **l, const char *path) {
1372 char **i;
1373
1374 STRV_FOREACH(i, l)
1375 if (path_equal(*i, path))
1376 return true;
1377
1378 return false;
1379 }
1380
1381 bool prefixed_path_strv_contains(char **l, const char *path) {
1382 char **i, *j;
1383
1384 STRV_FOREACH(i, l) {
1385 j = *i;
1386 if (*j == '-')
1387 j++;
1388 if (*j == '+')
1389 j++;
1390 if (path_equal(j, path))
1391 return true;
1392 }
1393
1394 return false;
1395 }