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