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