]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/path-util.c
parse-util: rework parse_dev() based on safe_atou() and DEVICE_MAJOR_VALID()/DEVICE_M...
[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 *
afbae3e9
TH
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
afbae3e9
TH
342 if (isempty(path))
343 return path;
344
858d36c1
YW
345 absolute = path_is_absolute(path);
346
347 f = path;
348 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/')) {
349 ignore_slash = true;
350 f++;
351 }
352
353 for (t = path; *f; f++) {
9eb977db
KS
354
355 if (*f == '/') {
356 slash = true;
357 continue;
358 }
359
360 if (slash) {
858d36c1
YW
361 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/'))
362 continue;
363
9eb977db 364 slash = false;
858d36c1
YW
365 if (ignore_slash)
366 ignore_slash = false;
367 else
368 *(t++) = '/';
9eb977db
KS
369 }
370
371 *(t++) = *f;
372 }
373
afbae3e9
TH
374 /* Special rule, if we stripped everything, we either need a "/" (for the root directory)
375 * or "." for the current directory */
376 if (t == path) {
377 if (absolute)
378 *(t++) = '/';
379 else
380 *(t++) = '.';
381 }
9eb977db
KS
382
383 *t = 0;
384 return path;
385}
386
424a19f8 387char* path_startswith(const char *path, const char *prefix) {
9eb977db
KS
388 assert(path);
389 assert(prefix);
390
0470289b
ZJS
391 /* Returns a pointer to the start of the first component after the parts matched by
392 * the prefix, iff
393 * - both paths are absolute or both paths are relative,
394 * and
395 * - each component in prefix in turn matches a component in path at the same position.
396 * An empty string will be returned when the prefix and path are equivalent.
397 *
398 * Returns NULL otherwise.
399 */
400
9eb977db 401 if ((path[0] == '/') != (prefix[0] == '/'))
424a19f8 402 return NULL;
9eb977db
KS
403
404 for (;;) {
405 size_t a, b;
406
407 path += strspn(path, "/");
408 prefix += strspn(prefix, "/");
409
410 if (*prefix == 0)
424a19f8 411 return (char*) path;
9eb977db
KS
412
413 if (*path == 0)
424a19f8 414 return NULL;
9eb977db
KS
415
416 a = strcspn(path, "/");
417 b = strcspn(prefix, "/");
418
419 if (a != b)
424a19f8 420 return NULL;
9eb977db
KS
421
422 if (memcmp(path, prefix, a) != 0)
424a19f8 423 return NULL;
9eb977db
KS
424
425 path += a;
426 prefix += b;
427 }
428}
429
2230852b
MS
430int path_compare(const char *a, const char *b) {
431 int d;
432
9eb977db
KS
433 assert(a);
434 assert(b);
435
f21f31b2 436 /* A relative path and an absolute path must not compare as equal.
2230852b
MS
437 * Which one is sorted before the other does not really matter.
438 * Here a relative path is ordered before an absolute path. */
439 d = (a[0] == '/') - (b[0] == '/');
373cd63a 440 if (d != 0)
2230852b 441 return d;
9eb977db
KS
442
443 for (;;) {
444 size_t j, k;
445
446 a += strspn(a, "/");
447 b += strspn(b, "/");
448
449 if (*a == 0 && *b == 0)
2230852b 450 return 0;
9eb977db 451
2230852b
MS
452 /* Order prefixes first: "/foo" before "/foo/bar" */
453 if (*a == 0)
454 return -1;
455 if (*b == 0)
456 return 1;
9eb977db
KS
457
458 j = strcspn(a, "/");
459 k = strcspn(b, "/");
460
2230852b
MS
461 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
462 d = memcmp(a, b, MIN(j, k));
373cd63a 463 if (d != 0)
2230852b 464 return (d > 0) - (d < 0); /* sign of d */
9eb977db 465
2230852b
MS
466 /* Sort "/foo/a" before "/foo/aaa" */
467 d = (j > k) - (j < k); /* sign of (j - k) */
373cd63a 468 if (d != 0)
2230852b 469 return d;
9eb977db
KS
470
471 a += j;
472 b += k;
473 }
474}
475
2230852b
MS
476bool path_equal(const char *a, const char *b) {
477 return path_compare(a, b) == 0;
478}
479
e3f791a2
ZJS
480bool path_equal_or_files_same(const char *a, const char *b, int flags) {
481 return path_equal(a, b) || files_same(a, b, flags) > 0;
c78e47a6
MS
482}
483
0c6ea3a4
ZJS
484char* path_join(const char *root, const char *path, const char *rest) {
485 assert(path);
486
487 if (!isempty(root))
bc854dc7 488 return strjoin(root, endswith(root, "/") ? "" : "/",
0c6ea3a4 489 path[0] == '/' ? path+1 : path,
bc854dc7 490 rest ? (endswith(path, "/") ? "" : "/") : NULL,
605405c6 491 rest && rest[0] == '/' ? rest+1 : rest);
0c6ea3a4
ZJS
492 else
493 return strjoin(path,
bc854dc7 494 rest ? (endswith(path, "/") ? "" : "/") : NULL,
605405c6 495 rest && rest[0] == '/' ? rest+1 : rest);
0c6ea3a4
ZJS
496}
497
85eca92e
LP
498int find_binary(const char *name, char **ret) {
499 int last_error, r;
500 const char *p;
501
c9d954b2 502 assert(name);
4087cb9e 503
571d0134 504 if (is_path(name)) {
85eca92e 505 if (access(name, X_OK) < 0)
b972115c
ZJS
506 return -errno;
507
85eca92e 508 if (ret) {
0f474365
LP
509 r = path_make_absolute_cwd(name, ret);
510 if (r < 0)
511 return r;
eb66db55 512 }
c9d954b2 513
c9d954b2 514 return 0;
85eca92e 515 }
c9d954b2 516
85eca92e
LP
517 /**
518 * Plain getenv, not secure_getenv, because we want
519 * to actually allow the user to pick the binary.
520 */
521 p = getenv("PATH");
522 if (!p)
523 p = DEFAULT_PATH;
524
525 last_error = -ENOENT;
526
527 for (;;) {
528 _cleanup_free_ char *j = NULL, *element = NULL;
529
530 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
531 if (r < 0)
532 return r;
533 if (r == 0)
534 break;
535
0f474365
LP
536 if (!path_is_absolute(element))
537 continue;
538
605405c6 539 j = strjoin(element, "/", name);
85eca92e
LP
540 if (!j)
541 return -ENOMEM;
542
543 if (access(j, X_OK) >= 0) {
544 /* Found it! */
c9d954b2 545
85eca92e 546 if (ret) {
858d36c1 547 *ret = path_simplify(j, false);
85eca92e 548 j = NULL;
eb66db55 549 }
c9d954b2
ZJS
550
551 return 0;
552 }
553
85eca92e 554 last_error = -errno;
c9d954b2 555 }
85eca92e
LP
556
557 return last_error;
c9d954b2 558}
8e184852 559
2ad8416d 560bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
8e184852 561 bool changed = false;
2ad8416d 562 const char* const* i;
8e184852 563
97f2d76d
TG
564 assert(timestamp);
565
234519ae 566 if (!paths)
4087cb9e 567 return false;
8e184852 568
4087cb9e 569 STRV_FOREACH(i, paths) {
8e184852 570 struct stat stats;
4087cb9e 571 usec_t u;
8e184852 572
4087cb9e 573 if (stat(*i, &stats) < 0)
8e184852
TG
574 continue;
575
4087cb9e
LP
576 u = timespec_load(&stats.st_mtim);
577
97f2d76d 578 /* first check */
4087cb9e 579 if (*timestamp >= u)
8e184852
TG
580 continue;
581
9f6445e3 582 log_debug("timestamp of '%s' changed", *i);
8e184852
TG
583
584 /* update timestamp */
4087cb9e
LP
585 if (update) {
586 *timestamp = u;
587 changed = true;
588 } else
589 return true;
8e184852 590 }
4087cb9e 591
8e184852
TG
592 return changed;
593}
eb66db55 594
5bcd08db 595static int binary_is_good(const char *binary) {
571d0134 596 _cleanup_free_ char *p = NULL, *d = NULL;
571d0134 597 int r;
eb66db55 598
85eca92e
LP
599 r = find_binary(binary, &p);
600 if (r == -ENOENT)
601 return 0;
571d0134
LP
602 if (r < 0)
603 return r;
604
061df014 605 /* An fsck that is linked to /bin/true is a non-existent
571d0134
LP
606 * fsck */
607
608 r = readlink_malloc(p, &d);
85eca92e
LP
609 if (r == -EINVAL) /* not a symlink */
610 return 1;
611 if (r < 0)
612 return r;
571d0134 613
3ae5990c
ZJS
614 return !PATH_IN_SET(d, "true"
615 "/bin/true",
616 "/usr/bin/true",
617 "/dev/null");
eb66db55 618}
1d13f648 619
5bcd08db
LP
620int fsck_exists(const char *fstype) {
621 const char *checker;
622
85eca92e 623 assert(fstype);
5bcd08db 624
85eca92e
LP
625 if (streq(fstype, "auto"))
626 return -EINVAL;
627
628 checker = strjoina("fsck.", fstype);
5bcd08db
LP
629 return binary_is_good(checker);
630}
631
632int mkfs_exists(const char *fstype) {
633 const char *mkfs;
634
85eca92e 635 assert(fstype);
5bcd08db 636
85eca92e
LP
637 if (streq(fstype, "auto"))
638 return -EINVAL;
639
640 mkfs = strjoina("mkfs.", fstype);
5bcd08db
LP
641 return binary_is_good(mkfs);
642}
643
1d13f648
LP
644char *prefix_root(const char *root, const char *path) {
645 char *n, *p;
646 size_t l;
647
648 /* If root is passed, prefixes path with it. Otherwise returns
649 * it as is. */
650
651 assert(path);
652
653 /* First, drop duplicate prefixing slashes from the path */
654 while (path[0] == '/' && path[1] == '/')
655 path++;
656
57ea45e1 657 if (empty_or_root(root))
1d13f648
LP
658 return strdup(path);
659
660 l = strlen(root) + 1 + strlen(path) + 1;
661
662 n = new(char, l);
663 if (!n)
664 return NULL;
665
666 p = stpcpy(n, root);
667
668 while (p > n && p[-1] == '/')
669 p--;
670
671 if (path[0] != '/')
672 *(p++) = '/';
673
674 strcpy(p, path);
675 return n;
676}
0f03c2a4
LP
677
678int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
679 char *p;
680 int r;
681
682 /*
683 * This function is intended to be used in command line
684 * parsers, to handle paths that are passed in. It makes the
685 * path absolute, and reduces it to NULL if omitted or
686 * root (the latter optionally).
687 *
688 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
689 * SUCCESS! Hence, do not pass in uninitialized pointers.
690 */
691
692 if (isempty(path)) {
693 *arg = mfree(*arg);
694 return 0;
695 }
696
697 r = path_make_absolute_cwd(path, &p);
698 if (r < 0)
699 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
700
858d36c1 701 path_simplify(p, false);
53e87b5a 702 if (suppress_root && empty_or_root(p))
0f03c2a4
LP
703 p = mfree(p);
704
858d36c1 705 free_and_replace(*arg, p);
53e87b5a 706
0f03c2a4
LP
707 return 0;
708}
5f311f8c
LP
709
710char* dirname_malloc(const char *path) {
711 char *d, *dir, *dir2;
712
713 assert(path);
714
715 d = strdup(path);
716 if (!d)
717 return NULL;
718
719 dir = dirname(d);
720 assert(dir);
721
722 if (dir == d)
723 return d;
724
725 dir2 = strdup(dir);
726 free(d);
727
728 return dir2;
729}
bb15fafe 730
b12d25a8 731const char *last_path_component(const char *path) {
8460289f
LP
732
733 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
734 *
b12d25a8
ZJS
735 * a/b/c → c
736 * a/b/c/ → c/
8460289f
LP
737 * x → x
738 * x/ → x/
739 * /y → y
740 * /y/ → y/
b12d25a8
ZJS
741 * / → /
742 * // → /
743 * /foo/a → a
744 * /foo/a/ → a/
8460289f
LP
745 *
746 * Also, the empty string is mapped to itself.
747 *
748 * This is different than basename(), which returns "" when a trailing slash is present.
b12d25a8
ZJS
749 */
750
751 unsigned l, k;
752
77e0a1b5
LP
753 if (!path)
754 return NULL;
755
b12d25a8 756 l = k = strlen(path);
69f9ccf1
ZJS
757 if (l == 0) /* special case — an empty string */
758 return path;
759
b12d25a8
ZJS
760 while (k > 0 && path[k-1] == '/')
761 k--;
762
763 if (k == 0) /* the root directory */
764 return path + l - 1;
765
766 while (k > 0 && path[k-1] != '/')
767 k--;
768
769 return path + k;
770}
771
a60c8eee
LP
772int path_extract_filename(const char *p, char **ret) {
773 _cleanup_free_ char *a = NULL;
774 const char *c, *e = NULL, *q;
775
776 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
777 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing slashes. */
778
779 if (!p)
780 return -EINVAL;
781
782 c = last_path_component(p);
783
784 for (q = c; *q != 0; q++)
785 if (*q != '/')
786 e = q + 1;
787
788 if (!e) /* no valid character? */
789 return -EINVAL;
790
791 a = strndup(c, e - c);
792 if (!a)
793 return -ENOMEM;
794
795 if (!filename_is_valid(a))
796 return -EINVAL;
797
798 *ret = TAKE_PTR(a);
799
800 return 0;
801}
802
bb15fafe
LP
803bool filename_is_valid(const char *p) {
804 const char *e;
805
806 if (isempty(p))
807 return false;
808
49bfc877 809 if (dot_or_dot_dot(p))
bb15fafe
LP
810 return false;
811
812 e = strchrnul(p, '/');
813 if (*e != 0)
814 return false;
815
656552eb 816 if (e - p > FILENAME_MAX) /* FILENAME_MAX is counted *without* the trailing NUL byte */
bb15fafe
LP
817 return false;
818
819 return true;
820}
821
656552eb 822bool path_is_valid(const char *p) {
bb15fafe
LP
823
824 if (isempty(p))
825 return false;
826
656552eb 827 if (strlen(p) >= PATH_MAX) /* PATH_MAX is counted *with* the trailing NUL byte */
49bfc877
LP
828 return false;
829
656552eb
LP
830 return true;
831}
832
833bool path_is_normalized(const char *p) {
834
835 if (!path_is_valid(p))
836 return false;
837
838 if (dot_or_dot_dot(p))
bb15fafe
LP
839 return false;
840
656552eb 841 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
bb15fafe
LP
842 return false;
843
49bfc877 844 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
bb15fafe
LP
845 return false;
846
847 if (strstr(p, "//"))
848 return false;
849
850 return true;
851}
a0956174
LP
852
853char *file_in_same_dir(const char *path, const char *filename) {
854 char *e, *ret;
855 size_t k;
856
857 assert(path);
858 assert(filename);
859
860 /* This removes the last component of path and appends
861 * filename, unless the latter is absolute anyway or the
862 * former isn't */
863
864 if (path_is_absolute(filename))
865 return strdup(filename);
866
867 e = strrchr(path, '/');
868 if (!e)
869 return strdup(filename);
870
871 k = strlen(filename);
872 ret = new(char, (e + 1 - path) + k + 1);
873 if (!ret)
874 return NULL;
875
876 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
877 return ret;
878}
879
55cdd057
ZJS
880bool hidden_or_backup_file(const char *filename) {
881 const char *p;
a0956174 882
a0956174
LP
883 assert(filename);
884
55cdd057
ZJS
885 if (filename[0] == '.' ||
886 streq(filename, "lost+found") ||
887 streq(filename, "aquota.user") ||
888 streq(filename, "aquota.group") ||
889 endswith(filename, "~"))
a0956174
LP
890 return true;
891
55cdd057
ZJS
892 p = strrchr(filename, '.');
893 if (!p)
894 return false;
895
941060bf
LP
896 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
897 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
898 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
899 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
900 * string. Specifically: there's now:
901 *
902 * The generic suffixes "~" and ".bak" for backup files
903 * The generic prefix "." for hidden files
904 *
94a0ef6e
ZJS
905 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
906 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
941060bf
LP
907 */
908
55cdd057
ZJS
909 return STR_IN_SET(p + 1,
910 "rpmnew",
911 "rpmsave",
912 "rpmorig",
913 "dpkg-old",
914 "dpkg-new",
915 "dpkg-tmp",
916 "dpkg-dist",
917 "dpkg-bak",
918 "dpkg-backup",
919 "dpkg-remove",
920 "ucf-new",
921 "ucf-old",
922 "ucf-dist",
941060bf 923 "swp",
94a0ef6e
ZJS
924 "bak",
925 "old",
926 "new");
a0956174
LP
927}
928
929bool is_device_path(const char *path) {
930
bae47ba7 931 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
a0956174 932
bae47ba7 933 return PATH_STARTSWITH_SET(path, "/dev/", "/sys/");
3ccb8862
ZJS
934}
935
57e84e75
LP
936bool valid_device_node_path(const char *path) {
937
938 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
939 * actual device node. */
940
941 if (!PATH_STARTSWITH_SET(path, "/dev/", "/run/systemd/inaccessible/"))
942 return false;
943
944 if (endswith(path, "/")) /* can't be a device node if it ends in a slash */
945 return false;
946
947 return path_is_normalized(path);
948}
949
950bool valid_device_allow_pattern(const char *path) {
951 assert(path);
952
953 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
954 * accept it */
955
49fe5c09 956 if (STARTSWITH_SET(path, "block-", "char-"))
57e84e75
LP
957 return true;
958
959 return valid_device_node_path(path);
a0956174 960}
5a46d55f
ZJS
961
962int systemd_installation_has_version(const char *root, unsigned minimal_version) {
963 const char *pattern;
964 int r;
965
966 /* Try to guess if systemd installation is later than the specified version. This
967 * is hacky and likely to yield false negatives, particularly if the installation
968 * is non-standard. False positives should be relatively rare.
969 */
970
971 NULSTR_FOREACH(pattern,
972 /* /lib works for systems without usr-merge, and for systems with a sane
973 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
974 * for Gentoo which does a merge without making /lib a symlink.
975 */
976 "lib/systemd/libsystemd-shared-*.so\0"
28faeda4
LP
977 "lib64/systemd/libsystemd-shared-*.so\0"
978 "usr/lib/systemd/libsystemd-shared-*.so\0"
979 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
5a46d55f
ZJS
980
981 _cleanup_strv_free_ char **names = NULL;
982 _cleanup_free_ char *path = NULL;
983 char *c, **name;
984
985 path = prefix_root(root, pattern);
986 if (!path)
987 return -ENOMEM;
988
989 r = glob_extend(&names, path);
990 if (r == -ENOENT)
991 continue;
992 if (r < 0)
993 return r;
994
dcd6361e 995 assert_se(c = endswith(path, "*.so"));
5a46d55f
ZJS
996 *c = '\0'; /* truncate the glob part */
997
998 STRV_FOREACH(name, names) {
999 /* This is most likely to run only once, hence let's not optimize anything. */
1000 char *t, *t2;
1001 unsigned version;
1002
1003 t = startswith(*name, path);
1004 if (!t)
1005 continue;
1006
1007 t2 = endswith(t, ".so");
1008 if (!t2)
1009 continue;
1010
1011 t2[0] = '\0'; /* truncate the suffix */
1012
1013 r = safe_atou(t, &version);
1014 if (r < 0) {
1015 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
1016 continue;
1017 }
1018
1019 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1020 *name, version,
1021 version >= minimal_version ? "OK" : "too old");
1022 if (version >= minimal_version)
1023 return true;
1024 }
1025 }
1026
1027 return false;
1028}
49bfc877
LP
1029
1030bool dot_or_dot_dot(const char *path) {
1031 if (!path)
1032 return false;
1033 if (path[0] != '.')
1034 return false;
1035 if (path[1] == 0)
1036 return true;
1037 if (path[1] != '.')
1038 return false;
1039
1040 return path[2] == 0;
1041}
57ea45e1
LP
1042
1043bool empty_or_root(const char *root) {
1044
1045 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1046 * i.e. either / or NULL or the empty string or any equivalent. */
1047
1048 if (!root)
1049 return true;
1050
1051 return root[strspn(root, "/")] == 0;
1052}
58a53add
YW
1053
1054int path_simplify_and_warn(
1055 char *path,
1056 unsigned flag,
1057 const char *unit,
1058 const char *filename,
1059 unsigned line,
1060 const char *lvalue) {
1061
5c270a18 1062 bool absolute, fatal = flag & PATH_CHECK_FATAL;
58a53add 1063
5c270a18 1064 assert(!FLAGS_SET(flag, PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE));
58a53add
YW
1065
1066 if (!utf8_is_valid(path)) {
1067 log_syntax_invalid_utf8(unit, LOG_ERR, filename, line, path);
1068 return -EINVAL;
1069 }
1070
1071 if (flag & (PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE)) {
1072 absolute = path_is_absolute(path);
1073
1074 if (!absolute && (flag & PATH_CHECK_ABSOLUTE)) {
1075 log_syntax(unit, LOG_ERR, filename, line, 0,
1076 "%s= path is not absolute%s: %s",
86ab333d 1077 lvalue, fatal ? "" : ", ignoring", path);
58a53add
YW
1078 return -EINVAL;
1079 }
1080
1081 if (absolute && (flag & PATH_CHECK_RELATIVE)) {
1082 log_syntax(unit, LOG_ERR, filename, line, 0,
1083 "%s= path is absolute%s: %s",
86ab333d 1084 lvalue, fatal ? "" : ", ignoring", path);
58a53add
YW
1085 return -EINVAL;
1086 }
1087 }
1088
1089 path_simplify(path, true);
1090
1091 if (!path_is_normalized(path)) {
1092 log_syntax(unit, LOG_ERR, filename, line, 0,
1093 "%s= path is not normalized%s: %s",
86ab333d 1094 lvalue, fatal ? "" : ", ignoring", path);
58a53add
YW
1095 return -EINVAL;
1096 }
1097
1098 return 0;
1099}