]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/path-util.c
test/networkd-test: in bridge test, wait for online after restart systemd-networkd
[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
7cb9c51c 110int path_make_relative(const char *from_dir, const char *to_path, char **_r) {
48054262
YW
111 char *f, *t, *r, *p;
112 unsigned n_parents = 0;
7cb9c51c
TK
113
114 assert(from_dir);
115 assert(to_path);
116 assert(_r);
117
118 /* Strips the common part, and adds ".." elements as necessary. */
119
48054262 120 if (!path_is_absolute(from_dir) || !path_is_absolute(to_path))
7cb9c51c
TK
121 return -EINVAL;
122
48054262
YW
123 f = strdupa(from_dir);
124 t = strdupa(to_path);
125
126 path_simplify(f, true);
127 path_simplify(t, true);
7cb9c51c
TK
128
129 /* Skip the common part. */
130 for (;;) {
2a5beb66 131 size_t a, b;
7cb9c51c 132
48054262
YW
133 f += *f == '/';
134 t += *t == '/';
7cb9c51c 135
48054262
YW
136 if (!*f) {
137 if (!*t)
7cb9c51c
TK
138 /* from_dir equals to_path. */
139 r = strdup(".");
140 else
141 /* from_dir is a parent directory of to_path. */
48054262 142 r = strdup(t);
7cb9c51c
TK
143 if (!r)
144 return -ENOMEM;
145
146 *_r = r;
147 return 0;
148 }
149
48054262 150 if (!*t)
7cb9c51c
TK
151 break;
152
48054262
YW
153 a = strcspn(f, "/");
154 b = strcspn(t, "/");
7cb9c51c 155
48054262 156 if (a != b || memcmp(f, t, a) != 0)
7cb9c51c
TK
157 break;
158
48054262
YW
159 f += a;
160 t += b;
7cb9c51c
TK
161 }
162
163 /* If we're here, then "from_dir" has one or more elements that need to
164 * be replaced with "..". */
165
166 /* Count the number of necessary ".." elements. */
48054262 167 for (; *f;) {
2a5beb66
LP
168 size_t w;
169
48054262 170 w = strcspn(f, "/");
2a5beb66
LP
171
172 /* If this includes ".." we can't do a simple series of "..", refuse */
48054262 173 if (w == 2 && f[0] == '.' && f[1] == '.')
2a5beb66
LP
174 return -EINVAL;
175
48054262
YW
176 /* Count number of elements */
177 n_parents++;
2a5beb66 178
48054262
YW
179 f += w;
180 f += *f == '/';
7cb9c51c
TK
181 }
182
48054262 183 r = new(char, n_parents * 3 + strlen(t) + 1);
7cb9c51c
TK
184 if (!r)
185 return -ENOMEM;
186
2a5beb66
LP
187 for (p = r; n_parents > 0; n_parents--)
188 p = mempcpy(p, "../", 3);
7cb9c51c 189
48054262
YW
190 if (*t)
191 strcpy(p, t);
192 else
193 /* Remove trailing slash */
194 *(--p) = 0;
7cb9c51c
TK
195
196 *_r = r;
197 return 0;
198}
199
cc4d7d81
ZJS
200char* path_startswith_strv(const char *p, char **set) {
201 char **s, *t;
202
203 STRV_FOREACH(s, set) {
204 t = path_startswith(p, *s);
205 if (t)
206 return t;
207 }
208
209 return NULL;
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;
c6134d3e 258 t = path_join(root, orig);
112cfb18
MM
259 if (!t) {
260 enomem = true;
261 continue;
262 }
12ed81d9 263 } else
112cfb18 264 t = *s;
9eb977db 265
a5648b80 266 r = chase_symlinks(t, root, 0, &u, NULL);
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
b47aa73a
ZJS
387int path_simplify_and_warn(
388 char *path,
389 unsigned flag,
390 const char *unit,
391 const char *filename,
392 unsigned line,
393 const char *lvalue) {
394
395 bool fatal = flag & PATH_CHECK_FATAL;
396
397 assert(!FLAGS_SET(flag, PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE));
398
399 if (!utf8_is_valid(path))
400 return log_syntax_invalid_utf8(unit, LOG_ERR, filename, line, path);
401
402 if (flag & (PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE)) {
403 bool absolute;
404
405 absolute = path_is_absolute(path);
406
407 if (!absolute && (flag & PATH_CHECK_ABSOLUTE))
408 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
409 "%s= path is not absolute%s: %s",
410 lvalue, fatal ? "" : ", ignoring", path);
411
412 if (absolute && (flag & PATH_CHECK_RELATIVE))
413 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
414 "%s= path is absolute%s: %s",
415 lvalue, fatal ? "" : ", ignoring", path);
416 }
417
418 path_simplify(path, true);
419
420 if (!path_is_valid(path))
421 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
422 "%s= path has invalid length (%zu bytes)%s.",
423 lvalue, strlen(path), fatal ? "" : ", ignoring");
424
425 if (!path_is_normalized(path))
426 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
427 "%s= path is not normalized%s: %s",
428 lvalue, fatal ? "" : ", ignoring", path);
429
430 return 0;
431}
432
424a19f8 433char* path_startswith(const char *path, const char *prefix) {
9eb977db
KS
434 assert(path);
435 assert(prefix);
436
0470289b
ZJS
437 /* Returns a pointer to the start of the first component after the parts matched by
438 * the prefix, iff
439 * - both paths are absolute or both paths are relative,
440 * and
441 * - each component in prefix in turn matches a component in path at the same position.
442 * An empty string will be returned when the prefix and path are equivalent.
443 *
444 * Returns NULL otherwise.
445 */
446
9eb977db 447 if ((path[0] == '/') != (prefix[0] == '/'))
424a19f8 448 return NULL;
9eb977db
KS
449
450 for (;;) {
451 size_t a, b;
452
453 path += strspn(path, "/");
454 prefix += strspn(prefix, "/");
455
456 if (*prefix == 0)
424a19f8 457 return (char*) path;
9eb977db
KS
458
459 if (*path == 0)
424a19f8 460 return NULL;
9eb977db
KS
461
462 a = strcspn(path, "/");
463 b = strcspn(prefix, "/");
464
465 if (a != b)
424a19f8 466 return NULL;
9eb977db
KS
467
468 if (memcmp(path, prefix, a) != 0)
424a19f8 469 return NULL;
9eb977db
KS
470
471 path += a;
472 prefix += b;
473 }
474}
475
2230852b
MS
476int path_compare(const char *a, const char *b) {
477 int d;
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. */
485 d = (a[0] == '/') - (b[0] == '/');
373cd63a 486 if (d != 0)
2230852b 487 return d;
9eb977db
KS
488
489 for (;;) {
490 size_t j, k;
491
492 a += strspn(a, "/");
493 b += strspn(b, "/");
494
495 if (*a == 0 && *b == 0)
2230852b 496 return 0;
9eb977db 497
2230852b
MS
498 /* Order prefixes first: "/foo" before "/foo/bar" */
499 if (*a == 0)
500 return -1;
501 if (*b == 0)
502 return 1;
9eb977db
KS
503
504 j = strcspn(a, "/");
505 k = strcspn(b, "/");
506
2230852b
MS
507 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
508 d = memcmp(a, b, MIN(j, k));
373cd63a 509 if (d != 0)
2230852b 510 return (d > 0) - (d < 0); /* sign of d */
9eb977db 511
2230852b
MS
512 /* Sort "/foo/a" before "/foo/aaa" */
513 d = (j > k) - (j < k); /* sign of (j - k) */
373cd63a 514 if (d != 0)
2230852b 515 return d;
9eb977db
KS
516
517 a += j;
518 b += k;
519 }
520}
521
2230852b
MS
522bool path_equal(const char *a, const char *b) {
523 return path_compare(a, b) == 0;
524}
525
e3f791a2
ZJS
526bool path_equal_or_files_same(const char *a, const char *b, int flags) {
527 return path_equal(a, b) || files_same(a, b, flags) > 0;
c78e47a6
MS
528}
529
727e63e3
LB
530bool path_equal_filename(const char *a, const char *b) {
531 _cleanup_free_ char *a_basename = NULL, *b_basename = NULL;
532 int r;
533
534 assert(a);
535 assert(b);
536
537 r = path_extract_filename(a, &a_basename);
538 if (r < 0) {
539 log_debug_errno(r, "Failed to parse basename of %s: %m", a);
540 return false;
541 }
542 r = path_extract_filename(b, &b_basename);
543 if (r < 0) {
544 log_debug_errno(r, "Failed to parse basename of %s: %m", b);
545 return false;
546 }
547
548 return path_equal(a_basename, b_basename);
549}
550
7ae27680
LP
551char* path_extend_internal(char **x, ...) {
552 size_t sz, old_sz;
553 char *q, *nx;
cd8194a3
LP
554 const char *p;
555 va_list ap;
556 bool slash;
cd8194a3 557
652ef298
ZJS
558 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings end/begin
559 * already with one so that it is unnecessary. Note that slashes which are already duplicate won't be
560 * removed. The string returned is hence always equal to or longer than the sum of the lengths of each
561 * individual string.
cd8194a3 562 *
7ae27680
LP
563 * The first argument may be an already allocated string that is extended via realloc() if
564 * non-NULL. path_extend() and path_join() are macro wrappers around this function, making use of the
565 * first parameter to distinguish the two operations.
566 *
cd8194a3
LP
567 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of which some
568 * are optional.
569 *
570 * Examples:
571 *
62a85ee0
ZJS
572 * path_join("foo", "bar") → "foo/bar"
573 * path_join("foo/", "bar") → "foo/bar"
574 * path_join("", "foo", "", "bar", "") → "foo/bar" */
cd8194a3 575
7ae27680
LP
576 sz = old_sz = x ? strlen_ptr(*x) : 0;
577 va_start(ap, x);
578 while ((p = va_arg(ap, char*)) != POINTER_MAX) {
579 size_t add;
580
581 if (isempty(p))
582 continue;
583
584 add = 1 + strlen(p);
585 if (sz > SIZE_MAX - add) /* overflow check */
586 return NULL;
587
588 sz += add;
589 }
590
cd8194a3
LP
591 va_end(ap);
592
7ae27680
LP
593 nx = realloc(x ? *x : NULL, GREEDY_ALLOC_ROUND_UP(sz+1));
594 if (!nx)
cd8194a3 595 return NULL;
7ae27680
LP
596 if (x)
597 *x = nx;
cd8194a3 598
7ae27680
LP
599 if (old_sz > 0)
600 slash = nx[old_sz] == '/';
601 else {
602 nx[old_sz] = 0;
cd8194a3
LP
603 slash = true; /* no need to generate a slash anymore */
604 }
605
7ae27680
LP
606 q = nx + old_sz;
607
608 va_start(ap, x);
66032ef4 609 while ((p = va_arg(ap, char*)) != POINTER_MAX) {
652ef298 610 if (isempty(p))
cd8194a3
LP
611 continue;
612
613 if (!slash && p[0] != '/')
614 *(q++) = '/';
615
616 q = stpcpy(q, p);
617 slash = endswith(p, "/");
618 }
619 va_end(ap);
620
7ae27680 621 return nx;
cd8194a3
LP
622}
623
5ca9139a 624static int check_x_access(const char *path, int *ret_fd) {
ece852c8 625 _cleanup_close_ int fd = -1;
ece852c8 626 int r;
5ca9139a 627
888f65ac
YW
628 /* We need to use O_PATH because there may be executables for which we have only exec
629 * permissions, but not read (usually suid executables). */
630 fd = open(path, O_PATH|O_CLOEXEC);
631 if (fd < 0)
632 return -errno;
ece852c8 633
888f65ac
YW
634 r = fd_verify_regular(fd);
635 if (r < 0)
636 return r;
ece852c8 637
888f65ac
YW
638 r = access_fd(fd, X_OK);
639 if (r < 0)
640 return r;
ece852c8
YW
641
642 if (ret_fd)
643 *ret_fd = TAKE_FD(fd);
644
5ca9139a
ZJS
645 return 0;
646}
647
648int find_executable_full(const char *name, bool use_path_envvar, char **ret_filename, int *ret_fd) {
85eca92e 649 int last_error, r;
92673045 650 const char *p = NULL;
85eca92e 651
c9d954b2 652 assert(name);
4087cb9e 653
571d0134 654 if (is_path(name)) {
5ca9139a 655 _cleanup_close_ int fd = -1;
b972115c 656
5ca9139a
ZJS
657 r = check_x_access(name, ret_fd ? &fd : NULL);
658 if (r < 0)
659 return r;
660
661 if (ret_filename) {
662 r = path_make_absolute_cwd(name, ret_filename);
0f474365
LP
663 if (r < 0)
664 return r;
eb66db55 665 }
c9d954b2 666
5ca9139a
ZJS
667 if (ret_fd)
668 *ret_fd = TAKE_FD(fd);
669
c9d954b2 670 return 0;
85eca92e 671 }
c9d954b2 672
92673045
ZJS
673 if (use_path_envvar)
674 /* Plain getenv, not secure_getenv, because we want to actually allow the user to pick the
675 * binary. */
676 p = getenv("PATH");
85eca92e
LP
677 if (!p)
678 p = DEFAULT_PATH;
679
680 last_error = -ENOENT;
681
5ca9139a 682 /* Resolve a single-component name to a full path */
85eca92e 683 for (;;) {
4ede9802 684 _cleanup_free_ char *element = NULL;
5ca9139a 685 _cleanup_close_ int fd = -1;
85eca92e
LP
686
687 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
688 if (r < 0)
689 return r;
690 if (r == 0)
691 break;
692
0f474365
LP
693 if (!path_is_absolute(element))
694 continue;
695
4ede9802 696 if (!path_extend(&element, name))
85eca92e
LP
697 return -ENOMEM;
698
4ede9802 699 r = check_x_access(element, ret_fd ? &fd : NULL);
ece852c8
YW
700 if (r < 0) {
701 /* PATH entries which we don't have access to are ignored, as per tradition. */
702 if (r != -EACCES)
703 last_error = r;
704 continue;
c9d954b2
ZJS
705 }
706
ece852c8
YW
707 /* Found it! */
708 if (ret_filename)
4ede9802 709 *ret_filename = path_simplify(TAKE_PTR(element), false);
ece852c8
YW
710 if (ret_fd)
711 *ret_fd = TAKE_FD(fd);
712
713 return 0;
c9d954b2 714 }
85eca92e
LP
715
716 return last_error;
c9d954b2 717}
8e184852 718
2ad8416d 719bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
8e184852 720 bool changed = false;
2ad8416d 721 const char* const* i;
8e184852 722
97f2d76d
TG
723 assert(timestamp);
724
234519ae 725 if (!paths)
4087cb9e 726 return false;
8e184852 727
4087cb9e 728 STRV_FOREACH(i, paths) {
8e184852 729 struct stat stats;
4087cb9e 730 usec_t u;
8e184852 731
4087cb9e 732 if (stat(*i, &stats) < 0)
8e184852
TG
733 continue;
734
4087cb9e
LP
735 u = timespec_load(&stats.st_mtim);
736
97f2d76d 737 /* first check */
4087cb9e 738 if (*timestamp >= u)
8e184852
TG
739 continue;
740
9f6445e3 741 log_debug("timestamp of '%s' changed", *i);
8e184852
TG
742
743 /* update timestamp */
4087cb9e
LP
744 if (update) {
745 *timestamp = u;
746 changed = true;
747 } else
748 return true;
8e184852 749 }
4087cb9e 750
8e184852
TG
751 return changed;
752}
eb66db55 753
f7bc0c32 754static int executable_is_good(const char *executable) {
571d0134 755 _cleanup_free_ char *p = NULL, *d = NULL;
571d0134 756 int r;
eb66db55 757
f7bc0c32 758 r = find_executable(executable, &p);
85eca92e
LP
759 if (r == -ENOENT)
760 return 0;
571d0134
LP
761 if (r < 0)
762 return r;
763
f7bc0c32 764 /* An fsck that is linked to /bin/true is a non-existent fsck */
571d0134
LP
765
766 r = readlink_malloc(p, &d);
85eca92e
LP
767 if (r == -EINVAL) /* not a symlink */
768 return 1;
769 if (r < 0)
770 return r;
571d0134 771
3ae5990c
ZJS
772 return !PATH_IN_SET(d, "true"
773 "/bin/true",
774 "/usr/bin/true",
775 "/dev/null");
eb66db55 776}
1d13f648 777
5bcd08db
LP
778int fsck_exists(const char *fstype) {
779 const char *checker;
780
85eca92e 781 assert(fstype);
5bcd08db 782
85eca92e
LP
783 if (streq(fstype, "auto"))
784 return -EINVAL;
785
786 checker = strjoina("fsck.", fstype);
f7bc0c32 787 return executable_is_good(checker);
5bcd08db
LP
788}
789
5f311f8c
LP
790char* dirname_malloc(const char *path) {
791 char *d, *dir, *dir2;
792
793 assert(path);
794
795 d = strdup(path);
796 if (!d)
797 return NULL;
798
799 dir = dirname(d);
800 assert(dir);
801
802 if (dir == d)
803 return d;
804
805 dir2 = strdup(dir);
806 free(d);
807
808 return dir2;
809}
bb15fafe 810
b12d25a8 811const char *last_path_component(const char *path) {
8460289f
LP
812
813 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
814 *
b12d25a8
ZJS
815 * a/b/c → c
816 * a/b/c/ → c/
8460289f
LP
817 * x → x
818 * x/ → x/
819 * /y → y
820 * /y/ → y/
b12d25a8
ZJS
821 * / → /
822 * // → /
823 * /foo/a → a
824 * /foo/a/ → a/
8460289f
LP
825 *
826 * Also, the empty string is mapped to itself.
827 *
828 * This is different than basename(), which returns "" when a trailing slash is present.
3cdcbdd3
LP
829 *
830 * This always succeeds (except if you pass NULL in which case it returns NULL, too).
b12d25a8
ZJS
831 */
832
833 unsigned l, k;
834
77e0a1b5
LP
835 if (!path)
836 return NULL;
837
b12d25a8 838 l = k = strlen(path);
69f9ccf1
ZJS
839 if (l == 0) /* special case — an empty string */
840 return path;
841
b12d25a8
ZJS
842 while (k > 0 && path[k-1] == '/')
843 k--;
844
845 if (k == 0) /* the root directory */
846 return path + l - 1;
847
848 while (k > 0 && path[k-1] != '/')
849 k--;
850
851 return path + k;
852}
853
a60c8eee
LP
854int path_extract_filename(const char *p, char **ret) {
855 _cleanup_free_ char *a = NULL;
3cdcbdd3 856 const char *c;
ee277c6b 857 size_t n;
a60c8eee
LP
858
859 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
ee277c6b
LP
860 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing
861 * slashes. Returns:
862 *
863 * -EINVAL → if the passed in path is not a valid path
864 * -EADDRNOTAVAIL → if only a directory was specified, but no filename, i.e. the root dir itself is specified
865 * -ENOMEM → no memory
866 *
867 * Returns >= 0 on success. If the input path has a trailing slash, returns O_DIRECTORY, to indicate
868 * the referenced file must be a directory.
869 *
870 * This function guarantees to return a fully valid filename, i.e. one that passes
871 * filename_is_valid() – this means "." and ".." are not accepted. */
a60c8eee 872
3cdcbdd3 873 if (!path_is_valid(p))
a60c8eee
LP
874 return -EINVAL;
875
3cdcbdd3
LP
876 /* Special case the root dir, because in that case we simply have no filename, but
877 * last_path_component() won't complain */
878 if (path_equal(p, "/"))
879 return -EADDRNOTAVAIL;
a60c8eee 880
3cdcbdd3 881 c = last_path_component(p);
ee277c6b 882 n = strcspn(c, "/");
a60c8eee 883
ee277c6b 884 a = strndup(c, n);
a60c8eee
LP
885 if (!a)
886 return -ENOMEM;
887
888 if (!filename_is_valid(a))
889 return -EINVAL;
890
891 *ret = TAKE_PTR(a);
ee277c6b 892 return c[n] == '/' ? O_DIRECTORY : 0;
a60c8eee
LP
893}
894
8dcb891c
LP
895int path_extract_directory(const char *p, char **ret) {
896 _cleanup_free_ char *a = NULL;
897 const char *c;
898
899 /* The inverse of path_extract_filename(), i.e. returns the directory path prefix. Returns:
900 *
901 * -EINVAL → if the passed in path is not a valid path
902 * -EDESTADDRREQ → if no directory was specified in the passed in path, i.e. only a filename was passed
903 * -EADDRNOTAVAIL → if the passed in parameter had no filename but did have a directory, i.e. the root dir itself was specified
904 * -ENOMEM → no memory (surprise!)
905 *
906 * This function guarantees to return a fully valid path, i.e. one that passes path_is_valid().
907 */
908
909 if (!path_is_valid(p))
910 return -EINVAL;
911
912 /* Special case the root dir, because otherwise for an input of "///" last_path_component() returns
913 * the pointer to the last slash only, which might be seen as a valid path below. */
914 if (path_equal(p, "/"))
915 return -EADDRNOTAVAIL;
916
917 c = last_path_component(p);
918
919 /* Delete trailing slashes, but keep one */
920 while (c > p+1 && c[-1] == '/')
921 c--;
922
923 if (p == c) /* No path whatsoever? Then return a recognizable error */
924 return -EDESTADDRREQ;
925
926 a = strndup(p, c - p);
927 if (!a)
928 return -ENOMEM;
929
930 if (!path_is_valid(a))
931 return -EINVAL;
932
933 *ret = TAKE_PTR(a);
934 return 0;
935}
936
bb15fafe
LP
937bool filename_is_valid(const char *p) {
938 const char *e;
939
940 if (isempty(p))
941 return false;
942
49bfc877 943 if (dot_or_dot_dot(p))
bb15fafe
LP
944 return false;
945
946 e = strchrnul(p, '/');
947 if (*e != 0)
948 return false;
949
2ef2376d 950 if (e - p > NAME_MAX) /* NAME_MAX is counted *without* the trailing NUL byte */
bb15fafe
LP
951 return false;
952
953 return true;
954}
955
656552eb 956bool path_is_valid(const char *p) {
bb15fafe
LP
957
958 if (isempty(p))
959 return false;
960
2ef2376d
LP
961 for (const char *e = p;;) {
962 size_t n;
49bfc877 963
2ef2376d
LP
964 /* Skip over slashes */
965 e += strspn(e, "/");
966 if (e - p >= PATH_MAX) /* Already reached the maximum length for a path? (PATH_MAX is counted
967 * *with* the trailing NUL byte) */
968 return false;
969 if (*e == 0) /* End of string? Yay! */
970 return true;
971
972 /* Skip over one component */
973 n = strcspn(e, "/");
974 if (n > NAME_MAX) /* One component larger than NAME_MAX? (NAME_MAX is counted *without* the
975 * trailing NUL byte) */
976 return false;
977
978 e += n;
979 }
656552eb
LP
980}
981
982bool path_is_normalized(const char *p) {
983
984 if (!path_is_valid(p))
985 return false;
986
987 if (dot_or_dot_dot(p))
bb15fafe
LP
988 return false;
989
656552eb 990 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
bb15fafe
LP
991 return false;
992
49bfc877 993 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
bb15fafe
LP
994 return false;
995
996 if (strstr(p, "//"))
997 return false;
998
999 return true;
1000}
a0956174
LP
1001
1002char *file_in_same_dir(const char *path, const char *filename) {
1003 char *e, *ret;
1004 size_t k;
1005
1006 assert(path);
1007 assert(filename);
1008
1009 /* This removes the last component of path and appends
1010 * filename, unless the latter is absolute anyway or the
1011 * former isn't */
1012
1013 if (path_is_absolute(filename))
1014 return strdup(filename);
1015
1016 e = strrchr(path, '/');
1017 if (!e)
1018 return strdup(filename);
1019
1020 k = strlen(filename);
1021 ret = new(char, (e + 1 - path) + k + 1);
1022 if (!ret)
1023 return NULL;
1024
1025 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
1026 return ret;
1027}
1028
55cdd057
ZJS
1029bool hidden_or_backup_file(const char *filename) {
1030 const char *p;
a0956174 1031
a0956174
LP
1032 assert(filename);
1033
55cdd057
ZJS
1034 if (filename[0] == '.' ||
1035 streq(filename, "lost+found") ||
1036 streq(filename, "aquota.user") ||
1037 streq(filename, "aquota.group") ||
1038 endswith(filename, "~"))
a0956174
LP
1039 return true;
1040
55cdd057
ZJS
1041 p = strrchr(filename, '.');
1042 if (!p)
1043 return false;
1044
941060bf
LP
1045 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
1046 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
1047 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
1048 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
1049 * string. Specifically: there's now:
1050 *
1051 * The generic suffixes "~" and ".bak" for backup files
1052 * The generic prefix "." for hidden files
1053 *
94a0ef6e
ZJS
1054 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
1055 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
941060bf
LP
1056 */
1057
55cdd057
ZJS
1058 return STR_IN_SET(p + 1,
1059 "rpmnew",
1060 "rpmsave",
1061 "rpmorig",
1062 "dpkg-old",
1063 "dpkg-new",
1064 "dpkg-tmp",
1065 "dpkg-dist",
1066 "dpkg-bak",
1067 "dpkg-backup",
1068 "dpkg-remove",
1069 "ucf-new",
1070 "ucf-old",
1071 "ucf-dist",
941060bf 1072 "swp",
94a0ef6e
ZJS
1073 "bak",
1074 "old",
1075 "new");
a0956174
LP
1076}
1077
1078bool is_device_path(const char *path) {
1079
bae47ba7 1080 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
a0956174 1081
bae47ba7 1082 return PATH_STARTSWITH_SET(path, "/dev/", "/sys/");
3ccb8862
ZJS
1083}
1084
57e84e75
LP
1085bool valid_device_node_path(const char *path) {
1086
1087 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
1088 * actual device node. */
1089
1090 if (!PATH_STARTSWITH_SET(path, "/dev/", "/run/systemd/inaccessible/"))
1091 return false;
1092
1093 if (endswith(path, "/")) /* can't be a device node if it ends in a slash */
1094 return false;
1095
1096 return path_is_normalized(path);
1097}
1098
1099bool valid_device_allow_pattern(const char *path) {
1100 assert(path);
1101
1102 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
1103 * accept it */
1104
49fe5c09 1105 if (STARTSWITH_SET(path, "block-", "char-"))
57e84e75
LP
1106 return true;
1107
1108 return valid_device_node_path(path);
a0956174 1109}
5a46d55f
ZJS
1110
1111int systemd_installation_has_version(const char *root, unsigned minimal_version) {
1112 const char *pattern;
1113 int r;
1114
1115 /* Try to guess if systemd installation is later than the specified version. This
1116 * is hacky and likely to yield false negatives, particularly if the installation
1117 * is non-standard. False positives should be relatively rare.
1118 */
1119
1120 NULSTR_FOREACH(pattern,
1121 /* /lib works for systems without usr-merge, and for systems with a sane
1122 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
1123 * for Gentoo which does a merge without making /lib a symlink.
1124 */
1125 "lib/systemd/libsystemd-shared-*.so\0"
28faeda4
LP
1126 "lib64/systemd/libsystemd-shared-*.so\0"
1127 "usr/lib/systemd/libsystemd-shared-*.so\0"
1128 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
5a46d55f
ZJS
1129
1130 _cleanup_strv_free_ char **names = NULL;
1131 _cleanup_free_ char *path = NULL;
1132 char *c, **name;
1133
c6134d3e 1134 path = path_join(root, pattern);
5a46d55f
ZJS
1135 if (!path)
1136 return -ENOMEM;
1137
544e146b 1138 r = glob_extend(&names, path, 0);
5a46d55f
ZJS
1139 if (r == -ENOENT)
1140 continue;
1141 if (r < 0)
1142 return r;
1143
dcd6361e 1144 assert_se(c = endswith(path, "*.so"));
5a46d55f
ZJS
1145 *c = '\0'; /* truncate the glob part */
1146
1147 STRV_FOREACH(name, names) {
1148 /* This is most likely to run only once, hence let's not optimize anything. */
1149 char *t, *t2;
1150 unsigned version;
1151
1152 t = startswith(*name, path);
1153 if (!t)
1154 continue;
1155
1156 t2 = endswith(t, ".so");
1157 if (!t2)
1158 continue;
1159
1160 t2[0] = '\0'; /* truncate the suffix */
1161
1162 r = safe_atou(t, &version);
1163 if (r < 0) {
1164 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
1165 continue;
1166 }
1167
1168 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1169 *name, version,
1170 version >= minimal_version ? "OK" : "too old");
1171 if (version >= minimal_version)
1172 return true;
1173 }
1174 }
1175
1176 return false;
1177}
49bfc877
LP
1178
1179bool dot_or_dot_dot(const char *path) {
1180 if (!path)
1181 return false;
1182 if (path[0] != '.')
1183 return false;
1184 if (path[1] == 0)
1185 return true;
1186 if (path[1] != '.')
1187 return false;
1188
1189 return path[2] == 0;
1190}
57ea45e1
LP
1191
1192bool empty_or_root(const char *root) {
1193
1194 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1195 * i.e. either / or NULL or the empty string or any equivalent. */
1196
1197 if (!root)
1198 return true;
1199
1200 return root[strspn(root, "/")] == 0;
1201}
3841fee8
LP
1202
1203bool path_strv_contains(char **l, const char *path) {
1204 char **i;
1205
1206 STRV_FOREACH(i, l)
1207 if (path_equal(*i, path))
1208 return true;
1209
1210 return false;
1211}
de46b2be
TM
1212
1213bool prefixed_path_strv_contains(char **l, const char *path) {
1214 char **i, *j;
1215
1216 STRV_FOREACH(i, l) {
1217 j = *i;
1218 if (*j == '-')
1219 j++;
1220 if (*j == '+')
1221 j++;
1222 if (path_equal(j, path))
1223 return true;
1224 }
1225
1226 return false;
1227}