]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/path-util.c
Merge pull request #17079 from keszybz/late-exec-resolution
[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_dir, const char *to_path, char **_r) {
111 char *f, *t, *r, *p;
112 unsigned n_parents = 0;
113
114 assert(from_dir);
115 assert(to_path);
116 assert(_r);
117
118 /* Strips the common part, and adds ".." elements as necessary. */
119
120 if (!path_is_absolute(from_dir) || !path_is_absolute(to_path))
121 return -EINVAL;
122
123 f = strdupa(from_dir);
124 t = strdupa(to_path);
125
126 path_simplify(f, true);
127 path_simplify(t, true);
128
129 /* Skip the common part. */
130 for (;;) {
131 size_t a, b;
132
133 f += *f == '/';
134 t += *t == '/';
135
136 if (!*f) {
137 if (!*t)
138 /* from_dir equals to_path. */
139 r = strdup(".");
140 else
141 /* from_dir is a parent directory of to_path. */
142 r = strdup(t);
143 if (!r)
144 return -ENOMEM;
145
146 *_r = r;
147 return 0;
148 }
149
150 if (!*t)
151 break;
152
153 a = strcspn(f, "/");
154 b = strcspn(t, "/");
155
156 if (a != b || memcmp(f, t, a) != 0)
157 break;
158
159 f += a;
160 t += b;
161 }
162
163 /* If we're here, then "from_dir" has one or more elements that need to
164 * be replaced with "..". */
165
166 /* Count the number of necessary ".." elements. */
167 for (; *f;) {
168 size_t w;
169
170 w = strcspn(f, "/");
171
172 /* If this includes ".." we can't do a simple series of "..", refuse */
173 if (w == 2 && f[0] == '.' && f[1] == '.')
174 return -EINVAL;
175
176 /* Count number of elements */
177 n_parents++;
178
179 f += w;
180 f += *f == '/';
181 }
182
183 r = new(char, n_parents * 3 + strlen(t) + 1);
184 if (!r)
185 return -ENOMEM;
186
187 for (p = r; n_parents > 0; n_parents--)
188 p = mempcpy(p, "../", 3);
189
190 if (*t)
191 strcpy(p, t);
192 else
193 /* Remove trailing slash */
194 *(--p) = 0;
195
196 *_r = r;
197 return 0;
198 }
199
200 char* path_startswith_strv(const char *p, char **set) {
201 char **s, *t;
202
203 STRV_FOREACH(s, set) {
204 t = path_startswith(p, *s);
205 if (t)
206 return t;
207 }
208
209 return NULL;
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 = path_join(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, NULL);
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 int path_simplify_and_warn(
388 char *path,
389 unsigned flag,
390 const char *unit,
391 const char *filename,
392 unsigned line,
393 const char *lvalue) {
394
395 bool fatal = flag & PATH_CHECK_FATAL;
396
397 assert(!FLAGS_SET(flag, PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE));
398
399 if (!utf8_is_valid(path))
400 return log_syntax_invalid_utf8(unit, LOG_ERR, filename, line, path);
401
402 if (flag & (PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE)) {
403 bool absolute;
404
405 absolute = path_is_absolute(path);
406
407 if (!absolute && (flag & PATH_CHECK_ABSOLUTE))
408 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
409 "%s= path is not absolute%s: %s",
410 lvalue, fatal ? "" : ", ignoring", path);
411
412 if (absolute && (flag & PATH_CHECK_RELATIVE))
413 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
414 "%s= path is absolute%s: %s",
415 lvalue, fatal ? "" : ", ignoring", path);
416 }
417
418 path_simplify(path, true);
419
420 if (!path_is_valid(path))
421 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
422 "%s= path has invalid length (%zu bytes)%s.",
423 lvalue, strlen(path), fatal ? "" : ", ignoring");
424
425 if (!path_is_normalized(path))
426 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
427 "%s= path is not normalized%s: %s",
428 lvalue, fatal ? "" : ", ignoring", path);
429
430 return 0;
431 }
432
433 char* path_startswith(const char *path, const char *prefix) {
434 assert(path);
435 assert(prefix);
436
437 /* Returns a pointer to the start of the first component after the parts matched by
438 * the prefix, iff
439 * - both paths are absolute or both paths are relative,
440 * and
441 * - each component in prefix in turn matches a component in path at the same position.
442 * An empty string will be returned when the prefix and path are equivalent.
443 *
444 * Returns NULL otherwise.
445 */
446
447 if ((path[0] == '/') != (prefix[0] == '/'))
448 return NULL;
449
450 for (;;) {
451 size_t a, b;
452
453 path += strspn(path, "/");
454 prefix += strspn(prefix, "/");
455
456 if (*prefix == 0)
457 return (char*) path;
458
459 if (*path == 0)
460 return NULL;
461
462 a = strcspn(path, "/");
463 b = strcspn(prefix, "/");
464
465 if (a != b)
466 return NULL;
467
468 if (memcmp(path, prefix, a) != 0)
469 return NULL;
470
471 path += a;
472 prefix += b;
473 }
474 }
475
476 int path_compare(const char *a, const char *b) {
477 int d;
478
479 assert(a);
480 assert(b);
481
482 /* A relative path and an absolute path must not compare as equal.
483 * Which one is sorted before the other does not really matter.
484 * Here a relative path is ordered before an absolute path. */
485 d = (a[0] == '/') - (b[0] == '/');
486 if (d != 0)
487 return d;
488
489 for (;;) {
490 size_t j, k;
491
492 a += strspn(a, "/");
493 b += strspn(b, "/");
494
495 if (*a == 0 && *b == 0)
496 return 0;
497
498 /* Order prefixes first: "/foo" before "/foo/bar" */
499 if (*a == 0)
500 return -1;
501 if (*b == 0)
502 return 1;
503
504 j = strcspn(a, "/");
505 k = strcspn(b, "/");
506
507 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
508 d = memcmp(a, b, MIN(j, k));
509 if (d != 0)
510 return (d > 0) - (d < 0); /* sign of d */
511
512 /* Sort "/foo/a" before "/foo/aaa" */
513 d = (j > k) - (j < k); /* sign of (j - k) */
514 if (d != 0)
515 return d;
516
517 a += j;
518 b += k;
519 }
520 }
521
522 bool path_equal(const char *a, const char *b) {
523 return path_compare(a, b) == 0;
524 }
525
526 bool path_equal_or_files_same(const char *a, const char *b, int flags) {
527 return path_equal(a, b) || files_same(a, b, flags) > 0;
528 }
529
530 char* path_join_internal(const char *first, ...) {
531 char *joined, *q;
532 const char *p;
533 va_list ap;
534 bool slash;
535 size_t sz;
536
537 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings end/begin
538 * already with one so that it is unnecessary. Note that slashes which are already duplicate won't be
539 * removed. The string returned is hence always equal to or longer than the sum of the lengths of each
540 * individual string.
541 *
542 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of which some
543 * are optional.
544 *
545 * Examples:
546 *
547 * path_join("foo", "bar") → "foo/bar"
548 * path_join("foo/", "bar") → "foo/bar"
549 * path_join("", "foo", "", "bar", "") → "foo/bar" */
550
551 sz = strlen_ptr(first);
552 va_start(ap, first);
553 while ((p = va_arg(ap, char*)) != POINTER_MAX)
554 if (!isempty(p))
555 sz += 1 + strlen(p);
556 va_end(ap);
557
558 joined = new(char, sz + 1);
559 if (!joined)
560 return NULL;
561
562 if (!isempty(first)) {
563 q = stpcpy(joined, first);
564 slash = endswith(first, "/");
565 } else {
566 /* Skip empty items */
567 joined[0] = 0;
568 q = joined;
569 slash = true; /* no need to generate a slash anymore */
570 }
571
572 va_start(ap, first);
573 while ((p = va_arg(ap, char*)) != POINTER_MAX) {
574 if (isempty(p))
575 continue;
576
577 if (!slash && p[0] != '/')
578 *(q++) = '/';
579
580 q = stpcpy(q, p);
581 slash = endswith(p, "/");
582 }
583 va_end(ap);
584
585 return joined;
586 }
587
588 static int check_x_access(const char *path, int *ret_fd) {
589 if (ret_fd) {
590 _cleanup_close_ int fd = -1;
591 int r;
592
593 /* We need to use O_PATH because there may be executables for which we have only exec
594 * permissions, but not read (usually suid executables). */
595 fd = open(path, O_PATH|O_CLOEXEC);
596 if (fd < 0)
597 return -errno;
598
599 r = access_fd(fd, X_OK);
600 if (r < 0)
601 return r;
602
603 *ret_fd = TAKE_FD(fd);
604 } else {
605 /* Let's optimize things a bit by not opening the file if we don't need the fd. */
606 if (access(path, X_OK) < 0)
607 return -errno;
608 }
609
610 return 0;
611 }
612
613 int find_executable_full(const char *name, bool use_path_envvar, char **ret_filename, int *ret_fd) {
614 int last_error, r;
615 const char *p = NULL;
616
617 assert(name);
618
619 if (is_path(name)) {
620 _cleanup_close_ int fd = -1;
621
622 r = check_x_access(name, ret_fd ? &fd : NULL);
623 if (r < 0)
624 return r;
625
626 if (ret_filename) {
627 r = path_make_absolute_cwd(name, ret_filename);
628 if (r < 0)
629 return r;
630 }
631
632 if (ret_fd)
633 *ret_fd = TAKE_FD(fd);
634
635 return 0;
636 }
637
638 if (use_path_envvar)
639 /* Plain getenv, not secure_getenv, because we want to actually allow the user to pick the
640 * binary. */
641 p = getenv("PATH");
642 if (!p)
643 p = DEFAULT_PATH;
644
645 last_error = -ENOENT;
646
647 /* Resolve a single-component name to a full path */
648 for (;;) {
649 _cleanup_free_ char *j = NULL, *element = NULL;
650 _cleanup_close_ int fd = -1;
651
652 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
653 if (r < 0)
654 return r;
655 if (r == 0)
656 break;
657
658 if (!path_is_absolute(element))
659 continue;
660
661 j = path_join(element, name);
662 if (!j)
663 return -ENOMEM;
664
665 r = check_x_access(j, ret_fd ? &fd : NULL);
666 if (r >= 0) {
667 _cleanup_free_ char *with_dash;
668
669 with_dash = strjoin(j, "/");
670 if (!with_dash)
671 return -ENOMEM;
672
673 /* If this passes, it must be a directory, and so should be skipped. */
674 if (access(with_dash, X_OK) >= 0)
675 continue;
676
677 /* We can't just `continue` inverting this case, since we need to update last_error. */
678 if (errno == ENOTDIR) {
679 /* Found it! */
680 if (ret_filename)
681 *ret_filename = path_simplify(TAKE_PTR(j), false);
682 if (ret_fd)
683 *ret_fd = TAKE_FD(fd);
684
685 return 0;
686 }
687 }
688
689 /* PATH entries which we don't have access to are ignored, as per tradition. */
690 if (errno != EACCES)
691 last_error = -errno;
692 }
693
694 return last_error;
695 }
696
697 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
698 bool changed = false;
699 const char* const* i;
700
701 assert(timestamp);
702
703 if (!paths)
704 return false;
705
706 STRV_FOREACH(i, paths) {
707 struct stat stats;
708 usec_t u;
709
710 if (stat(*i, &stats) < 0)
711 continue;
712
713 u = timespec_load(&stats.st_mtim);
714
715 /* first check */
716 if (*timestamp >= u)
717 continue;
718
719 log_debug("timestamp of '%s' changed", *i);
720
721 /* update timestamp */
722 if (update) {
723 *timestamp = u;
724 changed = true;
725 } else
726 return true;
727 }
728
729 return changed;
730 }
731
732 static int executable_is_good(const char *executable) {
733 _cleanup_free_ char *p = NULL, *d = NULL;
734 int r;
735
736 r = find_executable(executable, &p);
737 if (r == -ENOENT)
738 return 0;
739 if (r < 0)
740 return r;
741
742 /* An fsck that is linked to /bin/true is a non-existent fsck */
743
744 r = readlink_malloc(p, &d);
745 if (r == -EINVAL) /* not a symlink */
746 return 1;
747 if (r < 0)
748 return r;
749
750 return !PATH_IN_SET(d, "true"
751 "/bin/true",
752 "/usr/bin/true",
753 "/dev/null");
754 }
755
756 int fsck_exists(const char *fstype) {
757 const char *checker;
758
759 assert(fstype);
760
761 if (streq(fstype, "auto"))
762 return -EINVAL;
763
764 checker = strjoina("fsck.", fstype);
765 return executable_is_good(checker);
766 }
767
768 int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
769 char *p;
770 int r;
771
772 /*
773 * This function is intended to be used in command line
774 * parsers, to handle paths that are passed in. It makes the
775 * path absolute, and reduces it to NULL if omitted or
776 * root (the latter optionally).
777 *
778 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
779 * SUCCESS! Hence, do not pass in uninitialized pointers.
780 */
781
782 if (isempty(path)) {
783 *arg = mfree(*arg);
784 return 0;
785 }
786
787 r = path_make_absolute_cwd(path, &p);
788 if (r < 0)
789 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
790
791 path_simplify(p, false);
792 if (suppress_root && empty_or_root(p))
793 p = mfree(p);
794
795 free_and_replace(*arg, p);
796
797 return 0;
798 }
799
800 char* dirname_malloc(const char *path) {
801 char *d, *dir, *dir2;
802
803 assert(path);
804
805 d = strdup(path);
806 if (!d)
807 return NULL;
808
809 dir = dirname(d);
810 assert(dir);
811
812 if (dir == d)
813 return d;
814
815 dir2 = strdup(dir);
816 free(d);
817
818 return dir2;
819 }
820
821 const char *last_path_component(const char *path) {
822
823 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
824 *
825 * a/b/c → c
826 * a/b/c/ → c/
827 * x → x
828 * x/ → x/
829 * /y → y
830 * /y/ → y/
831 * / → /
832 * // → /
833 * /foo/a → a
834 * /foo/a/ → a/
835 *
836 * Also, the empty string is mapped to itself.
837 *
838 * This is different than basename(), which returns "" when a trailing slash is present.
839 */
840
841 unsigned l, k;
842
843 if (!path)
844 return NULL;
845
846 l = k = strlen(path);
847 if (l == 0) /* special case — an empty string */
848 return path;
849
850 while (k > 0 && path[k-1] == '/')
851 k--;
852
853 if (k == 0) /* the root directory */
854 return path + l - 1;
855
856 while (k > 0 && path[k-1] != '/')
857 k--;
858
859 return path + k;
860 }
861
862 int path_extract_filename(const char *p, char **ret) {
863 _cleanup_free_ char *a = NULL;
864 const char *c, *e = NULL, *q;
865
866 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
867 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing slashes. */
868
869 if (!p)
870 return -EINVAL;
871
872 c = last_path_component(p);
873
874 for (q = c; *q != 0; q++)
875 if (*q != '/')
876 e = q + 1;
877
878 if (!e) /* no valid character? */
879 return -EINVAL;
880
881 a = strndup(c, e - c);
882 if (!a)
883 return -ENOMEM;
884
885 if (!filename_is_valid(a))
886 return -EINVAL;
887
888 *ret = TAKE_PTR(a);
889
890 return 0;
891 }
892
893 bool filename_is_valid(const char *p) {
894 const char *e;
895
896 if (isempty(p))
897 return false;
898
899 if (dot_or_dot_dot(p))
900 return false;
901
902 e = strchrnul(p, '/');
903 if (*e != 0)
904 return false;
905
906 if (e - p > FILENAME_MAX) /* FILENAME_MAX is counted *without* the trailing NUL byte */
907 return false;
908
909 return true;
910 }
911
912 bool path_is_valid(const char *p) {
913
914 if (isempty(p))
915 return false;
916
917 if (strlen(p) >= PATH_MAX) /* PATH_MAX is counted *with* the trailing NUL byte */
918 return false;
919
920 return true;
921 }
922
923 bool path_is_normalized(const char *p) {
924
925 if (!path_is_valid(p))
926 return false;
927
928 if (dot_or_dot_dot(p))
929 return false;
930
931 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
932 return false;
933
934 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
935 return false;
936
937 if (strstr(p, "//"))
938 return false;
939
940 return true;
941 }
942
943 char *file_in_same_dir(const char *path, const char *filename) {
944 char *e, *ret;
945 size_t k;
946
947 assert(path);
948 assert(filename);
949
950 /* This removes the last component of path and appends
951 * filename, unless the latter is absolute anyway or the
952 * former isn't */
953
954 if (path_is_absolute(filename))
955 return strdup(filename);
956
957 e = strrchr(path, '/');
958 if (!e)
959 return strdup(filename);
960
961 k = strlen(filename);
962 ret = new(char, (e + 1 - path) + k + 1);
963 if (!ret)
964 return NULL;
965
966 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
967 return ret;
968 }
969
970 bool hidden_or_backup_file(const char *filename) {
971 const char *p;
972
973 assert(filename);
974
975 if (filename[0] == '.' ||
976 streq(filename, "lost+found") ||
977 streq(filename, "aquota.user") ||
978 streq(filename, "aquota.group") ||
979 endswith(filename, "~"))
980 return true;
981
982 p = strrchr(filename, '.');
983 if (!p)
984 return false;
985
986 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
987 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
988 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
989 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
990 * string. Specifically: there's now:
991 *
992 * The generic suffixes "~" and ".bak" for backup files
993 * The generic prefix "." for hidden files
994 *
995 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
996 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
997 */
998
999 return STR_IN_SET(p + 1,
1000 "rpmnew",
1001 "rpmsave",
1002 "rpmorig",
1003 "dpkg-old",
1004 "dpkg-new",
1005 "dpkg-tmp",
1006 "dpkg-dist",
1007 "dpkg-bak",
1008 "dpkg-backup",
1009 "dpkg-remove",
1010 "ucf-new",
1011 "ucf-old",
1012 "ucf-dist",
1013 "swp",
1014 "bak",
1015 "old",
1016 "new");
1017 }
1018
1019 bool is_device_path(const char *path) {
1020
1021 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
1022
1023 return PATH_STARTSWITH_SET(path, "/dev/", "/sys/");
1024 }
1025
1026 bool valid_device_node_path(const char *path) {
1027
1028 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
1029 * actual device node. */
1030
1031 if (!PATH_STARTSWITH_SET(path, "/dev/", "/run/systemd/inaccessible/"))
1032 return false;
1033
1034 if (endswith(path, "/")) /* can't be a device node if it ends in a slash */
1035 return false;
1036
1037 return path_is_normalized(path);
1038 }
1039
1040 bool valid_device_allow_pattern(const char *path) {
1041 assert(path);
1042
1043 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
1044 * accept it */
1045
1046 if (STARTSWITH_SET(path, "block-", "char-"))
1047 return true;
1048
1049 return valid_device_node_path(path);
1050 }
1051
1052 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
1053 const char *pattern;
1054 int r;
1055
1056 /* Try to guess if systemd installation is later than the specified version. This
1057 * is hacky and likely to yield false negatives, particularly if the installation
1058 * is non-standard. False positives should be relatively rare.
1059 */
1060
1061 NULSTR_FOREACH(pattern,
1062 /* /lib works for systems without usr-merge, and for systems with a sane
1063 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
1064 * for Gentoo which does a merge without making /lib a symlink.
1065 */
1066 "lib/systemd/libsystemd-shared-*.so\0"
1067 "lib64/systemd/libsystemd-shared-*.so\0"
1068 "usr/lib/systemd/libsystemd-shared-*.so\0"
1069 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
1070
1071 _cleanup_strv_free_ char **names = NULL;
1072 _cleanup_free_ char *path = NULL;
1073 char *c, **name;
1074
1075 path = path_join(root, pattern);
1076 if (!path)
1077 return -ENOMEM;
1078
1079 r = glob_extend(&names, path, 0);
1080 if (r == -ENOENT)
1081 continue;
1082 if (r < 0)
1083 return r;
1084
1085 assert_se(c = endswith(path, "*.so"));
1086 *c = '\0'; /* truncate the glob part */
1087
1088 STRV_FOREACH(name, names) {
1089 /* This is most likely to run only once, hence let's not optimize anything. */
1090 char *t, *t2;
1091 unsigned version;
1092
1093 t = startswith(*name, path);
1094 if (!t)
1095 continue;
1096
1097 t2 = endswith(t, ".so");
1098 if (!t2)
1099 continue;
1100
1101 t2[0] = '\0'; /* truncate the suffix */
1102
1103 r = safe_atou(t, &version);
1104 if (r < 0) {
1105 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
1106 continue;
1107 }
1108
1109 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1110 *name, version,
1111 version >= minimal_version ? "OK" : "too old");
1112 if (version >= minimal_version)
1113 return true;
1114 }
1115 }
1116
1117 return false;
1118 }
1119
1120 bool dot_or_dot_dot(const char *path) {
1121 if (!path)
1122 return false;
1123 if (path[0] != '.')
1124 return false;
1125 if (path[1] == 0)
1126 return true;
1127 if (path[1] != '.')
1128 return false;
1129
1130 return path[2] == 0;
1131 }
1132
1133 bool empty_or_root(const char *root) {
1134
1135 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1136 * i.e. either / or NULL or the empty string or any equivalent. */
1137
1138 if (!root)
1139 return true;
1140
1141 return root[strspn(root, "/")] == 0;
1142 }
1143
1144 bool path_strv_contains(char **l, const char *path) {
1145 char **i;
1146
1147 STRV_FOREACH(i, l)
1148 if (path_equal(*i, path))
1149 return true;
1150
1151 return false;
1152 }
1153
1154 bool prefixed_path_strv_contains(char **l, const char *path) {
1155 char **i, *j;
1156
1157 STRV_FOREACH(i, l) {
1158 j = *i;
1159 if (*j == '-')
1160 j++;
1161 if (*j == '+')
1162 j++;
1163 if (path_equal(j, path))
1164 return true;
1165 }
1166
1167 return false;
1168 }
1169
1170 bool credential_name_valid(const char *s) {
1171 /* We want that credential names are both valid in filenames (since that's our primary way to pass
1172 * them around) and as fdnames (which is how we might want to pass them around eventually) */
1173 return filename_is_valid(s) && fdname_is_valid(s);
1174 }