]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/path-util.c
tree-wide: replace strjoin() with path_join()
[thirdparty/systemd.git] / src / basic / path-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <limits.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <sys/stat.h>
9 #include <unistd.h>
10
11 /* When we include libgen.h because we need dirname() we immediately
12 * undefine basename() since libgen.h defines it as a macro to the
13 * POSIX version which is really broken. We prefer GNU basename(). */
14 #include <libgen.h>
15 #undef basename
16
17 #include "alloc-util.h"
18 #include "extract-word.h"
19 #include "fs-util.h"
20 #include "glob-util.h"
21 #include "log.h"
22 #include "macro.h"
23 #include "missing.h"
24 #include "nulstr-util.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 #include "stat-util.h"
28 #include "string-util.h"
29 #include "strv.h"
30 #include "time-util.h"
31 #include "utf8.h"
32
33 bool path_is_absolute(const char *p) {
34 return p[0] == '/';
35 }
36
37 bool is_path(const char *p) {
38 return !!strchr(p, '/');
39 }
40
41 int path_split_and_make_absolute(const char *p, char ***ret) {
42 char **l;
43 int r;
44
45 assert(p);
46 assert(ret);
47
48 l = strv_split(p, ":");
49 if (!l)
50 return -ENOMEM;
51
52 r = path_strv_make_absolute_cwd(l);
53 if (r < 0) {
54 strv_free(l);
55 return r;
56 }
57
58 *ret = l;
59 return r;
60 }
61
62 char *path_make_absolute(const char *p, const char *prefix) {
63 assert(p);
64
65 /* Makes every item in the list an absolute path by prepending
66 * the prefix, if specified and necessary */
67
68 if (path_is_absolute(p) || isempty(prefix))
69 return strdup(p);
70
71 return path_join(prefix, p);
72 }
73
74 int safe_getcwd(char **ret) {
75 char *cwd;
76
77 cwd = get_current_dir_name();
78 if (!cwd)
79 return negative_errno();
80
81 /* Let's make sure the directory is really absolute, to protect us from the logic behind
82 * CVE-2018-1000001 */
83 if (cwd[0] != '/') {
84 free(cwd);
85 return -ENOMEDIUM;
86 }
87
88 *ret = cwd;
89 return 0;
90 }
91
92 int path_make_absolute_cwd(const char *p, char **ret) {
93 char *c;
94 int r;
95
96 assert(p);
97 assert(ret);
98
99 /* Similar to path_make_absolute(), but prefixes with the
100 * current working directory. */
101
102 if (path_is_absolute(p))
103 c = strdup(p);
104 else {
105 _cleanup_free_ char *cwd = NULL;
106
107 r = safe_getcwd(&cwd);
108 if (r < 0)
109 return r;
110
111 c = path_join(cwd, p);
112 }
113 if (!c)
114 return -ENOMEM;
115
116 *ret = c;
117 return 0;
118 }
119
120 int path_make_relative(const char *from_dir, const char *to_path, char **_r) {
121 char *f, *t, *r, *p;
122 unsigned n_parents = 0;
123
124 assert(from_dir);
125 assert(to_path);
126 assert(_r);
127
128 /* Strips the common part, and adds ".." elements as necessary. */
129
130 if (!path_is_absolute(from_dir) || !path_is_absolute(to_path))
131 return -EINVAL;
132
133 f = strdupa(from_dir);
134 t = strdupa(to_path);
135
136 path_simplify(f, true);
137 path_simplify(t, true);
138
139 /* Skip the common part. */
140 for (;;) {
141 size_t a, b;
142
143 f += *f == '/';
144 t += *t == '/';
145
146 if (!*f) {
147 if (!*t)
148 /* from_dir equals to_path. */
149 r = strdup(".");
150 else
151 /* from_dir is a parent directory of to_path. */
152 r = strdup(t);
153 if (!r)
154 return -ENOMEM;
155
156 *_r = r;
157 return 0;
158 }
159
160 if (!*t)
161 break;
162
163 a = strcspn(f, "/");
164 b = strcspn(t, "/");
165
166 if (a != b || memcmp(f, t, a) != 0)
167 break;
168
169 f += a;
170 t += b;
171 }
172
173 /* If we're here, then "from_dir" has one or more elements that need to
174 * be replaced with "..". */
175
176 /* Count the number of necessary ".." elements. */
177 for (; *f;) {
178 size_t w;
179
180 w = strcspn(f, "/");
181
182 /* If this includes ".." we can't do a simple series of "..", refuse */
183 if (w == 2 && f[0] == '.' && f[1] == '.')
184 return -EINVAL;
185
186 /* Count number of elements */
187 n_parents++;
188
189 f += w;
190 f += *f == '/';
191 }
192
193 r = new(char, n_parents * 3 + strlen(t) + 1);
194 if (!r)
195 return -ENOMEM;
196
197 for (p = r; n_parents > 0; n_parents--)
198 p = mempcpy(p, "../", 3);
199
200 if (*t)
201 strcpy(p, t);
202 else
203 /* Remove trailing slash */
204 *(--p) = 0;
205
206 *_r = r;
207 return 0;
208 }
209
210 int path_strv_make_absolute_cwd(char **l) {
211 char **s;
212 int r;
213
214 /* Goes through every item in the string list and makes it
215 * absolute. This works in place and won't rollback any
216 * changes on failure. */
217
218 STRV_FOREACH(s, l) {
219 char *t;
220
221 r = path_make_absolute_cwd(*s, &t);
222 if (r < 0)
223 return r;
224
225 path_simplify(t, false);
226 free_and_replace(*s, t);
227 }
228
229 return 0;
230 }
231
232 char **path_strv_resolve(char **l, const char *root) {
233 char **s;
234 unsigned k = 0;
235 bool enomem = false;
236 int r;
237
238 if (strv_isempty(l))
239 return l;
240
241 /* Goes through every item in the string list and canonicalize
242 * the path. This works in place and won't rollback any
243 * changes on failure. */
244
245 STRV_FOREACH(s, l) {
246 _cleanup_free_ char *orig = NULL;
247 char *t, *u;
248
249 if (!path_is_absolute(*s)) {
250 free(*s);
251 continue;
252 }
253
254 if (root) {
255 orig = *s;
256 t = prefix_root(root, orig);
257 if (!t) {
258 enomem = true;
259 continue;
260 }
261 } else
262 t = *s;
263
264 r = chase_symlinks(t, root, 0, &u);
265 if (r == -ENOENT) {
266 if (root) {
267 u = TAKE_PTR(orig);
268 free(t);
269 } else
270 u = t;
271 } else if (r < 0) {
272 free(t);
273
274 if (r == -ENOMEM)
275 enomem = true;
276
277 continue;
278 } else if (root) {
279 char *x;
280
281 free(t);
282 x = path_startswith(u, root);
283 if (x) {
284 /* restore the slash if it was lost */
285 if (!startswith(x, "/"))
286 *(--x) = '/';
287
288 t = strdup(x);
289 free(u);
290 if (!t) {
291 enomem = true;
292 continue;
293 }
294 u = t;
295 } else {
296 /* canonicalized path goes outside of
297 * prefix, keep the original path instead */
298 free_and_replace(u, orig);
299 }
300 } else
301 free(t);
302
303 l[k++] = u;
304 }
305
306 l[k] = NULL;
307
308 if (enomem)
309 return NULL;
310
311 return l;
312 }
313
314 char **path_strv_resolve_uniq(char **l, const char *root) {
315
316 if (strv_isempty(l))
317 return l;
318
319 if (!path_strv_resolve(l, root))
320 return NULL;
321
322 return strv_uniq(l);
323 }
324
325 char *path_simplify(char *path, bool kill_dots) {
326 char *f, *t;
327 bool slash = false, ignore_slash = false, absolute;
328
329 assert(path);
330
331 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
332 * if kill_dots is true. Modifies the passed string in-place.
333 *
334 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
335 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
336 * .//./foo//./bar/. becomes ././foo/./bar/. (if kill_dots is false)
337 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
338 */
339
340 if (isempty(path))
341 return path;
342
343 absolute = path_is_absolute(path);
344
345 f = path;
346 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/')) {
347 ignore_slash = true;
348 f++;
349 }
350
351 for (t = path; *f; f++) {
352
353 if (*f == '/') {
354 slash = true;
355 continue;
356 }
357
358 if (slash) {
359 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/'))
360 continue;
361
362 slash = false;
363 if (ignore_slash)
364 ignore_slash = false;
365 else
366 *(t++) = '/';
367 }
368
369 *(t++) = *f;
370 }
371
372 /* Special rule, if we stripped everything, we either need a "/" (for the root directory)
373 * or "." for the current directory */
374 if (t == path) {
375 if (absolute)
376 *(t++) = '/';
377 else
378 *(t++) = '.';
379 }
380
381 *t = 0;
382 return path;
383 }
384
385 char* path_startswith(const char *path, const char *prefix) {
386 assert(path);
387 assert(prefix);
388
389 /* Returns a pointer to the start of the first component after the parts matched by
390 * the prefix, iff
391 * - both paths are absolute or both paths are relative,
392 * and
393 * - each component in prefix in turn matches a component in path at the same position.
394 * An empty string will be returned when the prefix and path are equivalent.
395 *
396 * Returns NULL otherwise.
397 */
398
399 if ((path[0] == '/') != (prefix[0] == '/'))
400 return NULL;
401
402 for (;;) {
403 size_t a, b;
404
405 path += strspn(path, "/");
406 prefix += strspn(prefix, "/");
407
408 if (*prefix == 0)
409 return (char*) path;
410
411 if (*path == 0)
412 return NULL;
413
414 a = strcspn(path, "/");
415 b = strcspn(prefix, "/");
416
417 if (a != b)
418 return NULL;
419
420 if (memcmp(path, prefix, a) != 0)
421 return NULL;
422
423 path += a;
424 prefix += b;
425 }
426 }
427
428 int path_compare(const char *a, const char *b) {
429 int d;
430
431 assert(a);
432 assert(b);
433
434 /* A relative path and an absolute path must not compare as equal.
435 * Which one is sorted before the other does not really matter.
436 * Here a relative path is ordered before an absolute path. */
437 d = (a[0] == '/') - (b[0] == '/');
438 if (d != 0)
439 return d;
440
441 for (;;) {
442 size_t j, k;
443
444 a += strspn(a, "/");
445 b += strspn(b, "/");
446
447 if (*a == 0 && *b == 0)
448 return 0;
449
450 /* Order prefixes first: "/foo" before "/foo/bar" */
451 if (*a == 0)
452 return -1;
453 if (*b == 0)
454 return 1;
455
456 j = strcspn(a, "/");
457 k = strcspn(b, "/");
458
459 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
460 d = memcmp(a, b, MIN(j, k));
461 if (d != 0)
462 return (d > 0) - (d < 0); /* sign of d */
463
464 /* Sort "/foo/a" before "/foo/aaa" */
465 d = (j > k) - (j < k); /* sign of (j - k) */
466 if (d != 0)
467 return d;
468
469 a += j;
470 b += k;
471 }
472 }
473
474 bool path_equal(const char *a, const char *b) {
475 return path_compare(a, b) == 0;
476 }
477
478 bool path_equal_or_files_same(const char *a, const char *b, int flags) {
479 return path_equal(a, b) || files_same(a, b, flags) > 0;
480 }
481
482 char* path_join_internal(const char *first, ...) {
483 char *joined, *q;
484 const char *p;
485 va_list ap;
486 bool slash;
487 size_t sz;
488
489 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings end/begin
490 * already with one so that it is unnecessary. Note that slashes which are already duplicate won't be
491 * removed. The string returned is hence always equal to or longer than the sum of the lengths of each
492 * individual string.
493 *
494 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of which some
495 * are optional.
496 *
497 * Examples:
498 *
499 * path_join("foo", "bar") → "foo/bar"
500 * path_join("foo/", "bar") → "foo/bar"
501 * path_join("", "foo", "", "bar", "") → "foo/bar" */
502
503 sz = strlen_ptr(first);
504 va_start(ap, first);
505 while ((p = va_arg(ap, char*)) != (const char*) -1)
506 if (!isempty(p))
507 sz += 1 + strlen(p);
508 va_end(ap);
509
510 joined = new(char, sz + 1);
511 if (!joined)
512 return NULL;
513
514 if (!isempty(first)) {
515 q = stpcpy(joined, first);
516 slash = endswith(first, "/");
517 } else {
518 /* Skip empty items */
519 joined[0] = 0;
520 q = joined;
521 slash = true; /* no need to generate a slash anymore */
522 }
523
524 va_start(ap, first);
525 while ((p = va_arg(ap, char*)) != (const char*) -1) {
526 if (isempty(p))
527 continue;
528
529 if (!slash && p[0] != '/')
530 *(q++) = '/';
531
532 q = stpcpy(q, p);
533 slash = endswith(p, "/");
534 }
535 va_end(ap);
536
537 return joined;
538 }
539
540 int find_binary(const char *name, char **ret) {
541 int last_error, r;
542 const char *p;
543
544 assert(name);
545
546 if (is_path(name)) {
547 if (access(name, X_OK) < 0)
548 return -errno;
549
550 if (ret) {
551 r = path_make_absolute_cwd(name, ret);
552 if (r < 0)
553 return r;
554 }
555
556 return 0;
557 }
558
559 /**
560 * Plain getenv, not secure_getenv, because we want
561 * to actually allow the user to pick the binary.
562 */
563 p = getenv("PATH");
564 if (!p)
565 p = DEFAULT_PATH;
566
567 last_error = -ENOENT;
568
569 for (;;) {
570 _cleanup_free_ char *j = NULL, *element = NULL;
571
572 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
573 if (r < 0)
574 return r;
575 if (r == 0)
576 break;
577
578 if (!path_is_absolute(element))
579 continue;
580
581 j = path_join(element, name);
582 if (!j)
583 return -ENOMEM;
584
585 if (access(j, X_OK) >= 0) {
586 /* Found it! */
587
588 if (ret) {
589 *ret = path_simplify(j, false);
590 j = NULL;
591 }
592
593 return 0;
594 }
595
596 last_error = -errno;
597 }
598
599 return last_error;
600 }
601
602 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
603 bool changed = false;
604 const char* const* i;
605
606 assert(timestamp);
607
608 if (!paths)
609 return false;
610
611 STRV_FOREACH(i, paths) {
612 struct stat stats;
613 usec_t u;
614
615 if (stat(*i, &stats) < 0)
616 continue;
617
618 u = timespec_load(&stats.st_mtim);
619
620 /* first check */
621 if (*timestamp >= u)
622 continue;
623
624 log_debug("timestamp of '%s' changed", *i);
625
626 /* update timestamp */
627 if (update) {
628 *timestamp = u;
629 changed = true;
630 } else
631 return true;
632 }
633
634 return changed;
635 }
636
637 static int binary_is_good(const char *binary) {
638 _cleanup_free_ char *p = NULL, *d = NULL;
639 int r;
640
641 r = find_binary(binary, &p);
642 if (r == -ENOENT)
643 return 0;
644 if (r < 0)
645 return r;
646
647 /* An fsck that is linked to /bin/true is a non-existent
648 * fsck */
649
650 r = readlink_malloc(p, &d);
651 if (r == -EINVAL) /* not a symlink */
652 return 1;
653 if (r < 0)
654 return r;
655
656 return !PATH_IN_SET(d, "true"
657 "/bin/true",
658 "/usr/bin/true",
659 "/dev/null");
660 }
661
662 int fsck_exists(const char *fstype) {
663 const char *checker;
664
665 assert(fstype);
666
667 if (streq(fstype, "auto"))
668 return -EINVAL;
669
670 checker = strjoina("fsck.", fstype);
671 return binary_is_good(checker);
672 }
673
674 int mkfs_exists(const char *fstype) {
675 const char *mkfs;
676
677 assert(fstype);
678
679 if (streq(fstype, "auto"))
680 return -EINVAL;
681
682 mkfs = strjoina("mkfs.", fstype);
683 return binary_is_good(mkfs);
684 }
685
686 char *prefix_root(const char *root, const char *path) {
687 char *n, *p;
688 size_t l;
689
690 /* If root is passed, prefixes path with it. Otherwise returns
691 * it as is. */
692
693 assert(path);
694
695 /* First, drop duplicate prefixing slashes from the path */
696 while (path[0] == '/' && path[1] == '/')
697 path++;
698
699 if (empty_or_root(root))
700 return strdup(path);
701
702 l = strlen(root) + 1 + strlen(path) + 1;
703
704 n = new(char, l);
705 if (!n)
706 return NULL;
707
708 p = stpcpy(n, root);
709
710 while (p > n && p[-1] == '/')
711 p--;
712
713 if (path[0] != '/')
714 *(p++) = '/';
715
716 strcpy(p, path);
717 return n;
718 }
719
720 int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
721 char *p;
722 int r;
723
724 /*
725 * This function is intended to be used in command line
726 * parsers, to handle paths that are passed in. It makes the
727 * path absolute, and reduces it to NULL if omitted or
728 * root (the latter optionally).
729 *
730 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
731 * SUCCESS! Hence, do not pass in uninitialized pointers.
732 */
733
734 if (isempty(path)) {
735 *arg = mfree(*arg);
736 return 0;
737 }
738
739 r = path_make_absolute_cwd(path, &p);
740 if (r < 0)
741 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
742
743 path_simplify(p, false);
744 if (suppress_root && empty_or_root(p))
745 p = mfree(p);
746
747 free_and_replace(*arg, p);
748
749 return 0;
750 }
751
752 char* dirname_malloc(const char *path) {
753 char *d, *dir, *dir2;
754
755 assert(path);
756
757 d = strdup(path);
758 if (!d)
759 return NULL;
760
761 dir = dirname(d);
762 assert(dir);
763
764 if (dir == d)
765 return d;
766
767 dir2 = strdup(dir);
768 free(d);
769
770 return dir2;
771 }
772
773 const char *last_path_component(const char *path) {
774
775 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
776 *
777 * a/b/c → c
778 * a/b/c/ → c/
779 * x → x
780 * x/ → x/
781 * /y → y
782 * /y/ → y/
783 * / → /
784 * // → /
785 * /foo/a → a
786 * /foo/a/ → a/
787 *
788 * Also, the empty string is mapped to itself.
789 *
790 * This is different than basename(), which returns "" when a trailing slash is present.
791 */
792
793 unsigned l, k;
794
795 if (!path)
796 return NULL;
797
798 l = k = strlen(path);
799 if (l == 0) /* special case — an empty string */
800 return path;
801
802 while (k > 0 && path[k-1] == '/')
803 k--;
804
805 if (k == 0) /* the root directory */
806 return path + l - 1;
807
808 while (k > 0 && path[k-1] != '/')
809 k--;
810
811 return path + k;
812 }
813
814 int path_extract_filename(const char *p, char **ret) {
815 _cleanup_free_ char *a = NULL;
816 const char *c, *e = NULL, *q;
817
818 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
819 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing slashes. */
820
821 if (!p)
822 return -EINVAL;
823
824 c = last_path_component(p);
825
826 for (q = c; *q != 0; q++)
827 if (*q != '/')
828 e = q + 1;
829
830 if (!e) /* no valid character? */
831 return -EINVAL;
832
833 a = strndup(c, e - c);
834 if (!a)
835 return -ENOMEM;
836
837 if (!filename_is_valid(a))
838 return -EINVAL;
839
840 *ret = TAKE_PTR(a);
841
842 return 0;
843 }
844
845 bool filename_is_valid(const char *p) {
846 const char *e;
847
848 if (isempty(p))
849 return false;
850
851 if (dot_or_dot_dot(p))
852 return false;
853
854 e = strchrnul(p, '/');
855 if (*e != 0)
856 return false;
857
858 if (e - p > FILENAME_MAX) /* FILENAME_MAX is counted *without* the trailing NUL byte */
859 return false;
860
861 return true;
862 }
863
864 bool path_is_valid(const char *p) {
865
866 if (isempty(p))
867 return false;
868
869 if (strlen(p) >= PATH_MAX) /* PATH_MAX is counted *with* the trailing NUL byte */
870 return false;
871
872 return true;
873 }
874
875 bool path_is_normalized(const char *p) {
876
877 if (!path_is_valid(p))
878 return false;
879
880 if (dot_or_dot_dot(p))
881 return false;
882
883 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
884 return false;
885
886 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
887 return false;
888
889 if (strstr(p, "//"))
890 return false;
891
892 return true;
893 }
894
895 char *file_in_same_dir(const char *path, const char *filename) {
896 char *e, *ret;
897 size_t k;
898
899 assert(path);
900 assert(filename);
901
902 /* This removes the last component of path and appends
903 * filename, unless the latter is absolute anyway or the
904 * former isn't */
905
906 if (path_is_absolute(filename))
907 return strdup(filename);
908
909 e = strrchr(path, '/');
910 if (!e)
911 return strdup(filename);
912
913 k = strlen(filename);
914 ret = new(char, (e + 1 - path) + k + 1);
915 if (!ret)
916 return NULL;
917
918 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
919 return ret;
920 }
921
922 bool hidden_or_backup_file(const char *filename) {
923 const char *p;
924
925 assert(filename);
926
927 if (filename[0] == '.' ||
928 streq(filename, "lost+found") ||
929 streq(filename, "aquota.user") ||
930 streq(filename, "aquota.group") ||
931 endswith(filename, "~"))
932 return true;
933
934 p = strrchr(filename, '.');
935 if (!p)
936 return false;
937
938 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
939 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
940 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
941 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
942 * string. Specifically: there's now:
943 *
944 * The generic suffixes "~" and ".bak" for backup files
945 * The generic prefix "." for hidden files
946 *
947 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
948 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
949 */
950
951 return STR_IN_SET(p + 1,
952 "rpmnew",
953 "rpmsave",
954 "rpmorig",
955 "dpkg-old",
956 "dpkg-new",
957 "dpkg-tmp",
958 "dpkg-dist",
959 "dpkg-bak",
960 "dpkg-backup",
961 "dpkg-remove",
962 "ucf-new",
963 "ucf-old",
964 "ucf-dist",
965 "swp",
966 "bak",
967 "old",
968 "new");
969 }
970
971 bool is_device_path(const char *path) {
972
973 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
974
975 return PATH_STARTSWITH_SET(path, "/dev/", "/sys/");
976 }
977
978 bool valid_device_node_path(const char *path) {
979
980 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
981 * actual device node. */
982
983 if (!PATH_STARTSWITH_SET(path, "/dev/", "/run/systemd/inaccessible/"))
984 return false;
985
986 if (endswith(path, "/")) /* can't be a device node if it ends in a slash */
987 return false;
988
989 return path_is_normalized(path);
990 }
991
992 bool valid_device_allow_pattern(const char *path) {
993 assert(path);
994
995 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
996 * accept it */
997
998 if (STARTSWITH_SET(path, "block-", "char-"))
999 return true;
1000
1001 return valid_device_node_path(path);
1002 }
1003
1004 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
1005 const char *pattern;
1006 int r;
1007
1008 /* Try to guess if systemd installation is later than the specified version. This
1009 * is hacky and likely to yield false negatives, particularly if the installation
1010 * is non-standard. False positives should be relatively rare.
1011 */
1012
1013 NULSTR_FOREACH(pattern,
1014 /* /lib works for systems without usr-merge, and for systems with a sane
1015 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
1016 * for Gentoo which does a merge without making /lib a symlink.
1017 */
1018 "lib/systemd/libsystemd-shared-*.so\0"
1019 "lib64/systemd/libsystemd-shared-*.so\0"
1020 "usr/lib/systemd/libsystemd-shared-*.so\0"
1021 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
1022
1023 _cleanup_strv_free_ char **names = NULL;
1024 _cleanup_free_ char *path = NULL;
1025 char *c, **name;
1026
1027 path = prefix_root(root, pattern);
1028 if (!path)
1029 return -ENOMEM;
1030
1031 r = glob_extend(&names, path);
1032 if (r == -ENOENT)
1033 continue;
1034 if (r < 0)
1035 return r;
1036
1037 assert_se(c = endswith(path, "*.so"));
1038 *c = '\0'; /* truncate the glob part */
1039
1040 STRV_FOREACH(name, names) {
1041 /* This is most likely to run only once, hence let's not optimize anything. */
1042 char *t, *t2;
1043 unsigned version;
1044
1045 t = startswith(*name, path);
1046 if (!t)
1047 continue;
1048
1049 t2 = endswith(t, ".so");
1050 if (!t2)
1051 continue;
1052
1053 t2[0] = '\0'; /* truncate the suffix */
1054
1055 r = safe_atou(t, &version);
1056 if (r < 0) {
1057 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
1058 continue;
1059 }
1060
1061 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1062 *name, version,
1063 version >= minimal_version ? "OK" : "too old");
1064 if (version >= minimal_version)
1065 return true;
1066 }
1067 }
1068
1069 return false;
1070 }
1071
1072 bool dot_or_dot_dot(const char *path) {
1073 if (!path)
1074 return false;
1075 if (path[0] != '.')
1076 return false;
1077 if (path[1] == 0)
1078 return true;
1079 if (path[1] != '.')
1080 return false;
1081
1082 return path[2] == 0;
1083 }
1084
1085 bool empty_or_root(const char *root) {
1086
1087 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1088 * i.e. either / or NULL or the empty string or any equivalent. */
1089
1090 if (!root)
1091 return true;
1092
1093 return root[strspn(root, "/")] == 0;
1094 }
1095
1096 int path_simplify_and_warn(
1097 char *path,
1098 unsigned flag,
1099 const char *unit,
1100 const char *filename,
1101 unsigned line,
1102 const char *lvalue) {
1103
1104 bool fatal = flag & PATH_CHECK_FATAL;
1105
1106 assert(!FLAGS_SET(flag, PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE));
1107
1108 if (!utf8_is_valid(path))
1109 return log_syntax_invalid_utf8(unit, LOG_ERR, filename, line, path);
1110
1111 if (flag & (PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE)) {
1112 bool absolute;
1113
1114 absolute = path_is_absolute(path);
1115
1116 if (!absolute && (flag & PATH_CHECK_ABSOLUTE))
1117 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
1118 "%s= path is not absolute%s: %s",
1119 lvalue, fatal ? "" : ", ignoring", path);
1120
1121 if (absolute && (flag & PATH_CHECK_RELATIVE))
1122 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
1123 "%s= path is absolute%s: %s",
1124 lvalue, fatal ? "" : ", ignoring", path);
1125 }
1126
1127 path_simplify(path, true);
1128
1129 if (!path_is_valid(path))
1130 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
1131 "%s= path has invalid length (%zu bytes)%s.",
1132 lvalue, strlen(path), fatal ? "" : ", ignoring");
1133
1134 if (!path_is_normalized(path))
1135 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
1136 "%s= path is not normalized%s: %s",
1137 lvalue, fatal ? "" : ", ignoring", path);
1138
1139 return 0;
1140 }