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