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