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