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