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