]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/path-util.c
Merge pull request #20837 from bluca/coveralls
[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
4ff361cc 148 path_simplify(result);
fe69c41e
YW
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
4ff361cc 194 path_simplify(result);
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
4ff361cc 230 path_simplify(t);
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
4ff361cc 330char *path_simplify(char *path) {
cb71ed91
YW
331 bool add_slash = false;
332 char *f = path;
333 int r;
9eb977db 334
858d36c1
YW
335 assert(path);
336
cb71ed91
YW
337 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots.
338 * Modifies the passed string in-place.
9eb977db 339 *
cb71ed91
YW
340 * ///foo//./bar/. becomes /foo/bar
341 * .//./foo//./bar/. becomes foo/bar
9eb977db
KS
342 */
343
afbae3e9
TH
344 if (isempty(path))
345 return path;
346
cb71ed91 347 if (path_is_absolute(path))
858d36c1 348 f++;
858d36c1 349
cb71ed91
YW
350 for (const char *p = f;;) {
351 const char *e;
9eb977db 352
cb71ed91
YW
353 r = path_find_first_component(&p, true, &e);
354 if (r == 0)
355 break;
9eb977db 356
cb71ed91
YW
357 if (add_slash)
358 *f++ = '/';
858d36c1 359
cb71ed91
YW
360 if (r < 0) {
361 /* if path is invalid, then refuse to simplify remaining part. */
362 memmove(f, p, strlen(p) + 1);
363 return path;
9eb977db
KS
364 }
365
cb71ed91
YW
366 memmove(f, e, r);
367 f += r;
9eb977db 368
cb71ed91 369 add_slash = true;
afbae3e9 370 }
9eb977db 371
cb71ed91
YW
372 /* Special rule, if we stripped everything, we need a "." for the current directory. */
373 if (f == path)
374 *f++ = '.';
375
376 *f = '\0';
9eb977db
KS
377 return path;
378}
379
b47aa73a
ZJS
380int path_simplify_and_warn(
381 char *path,
382 unsigned flag,
383 const char *unit,
384 const char *filename,
385 unsigned line,
386 const char *lvalue) {
387
388 bool fatal = flag & PATH_CHECK_FATAL;
389
390 assert(!FLAGS_SET(flag, PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE));
391
392 if (!utf8_is_valid(path))
393 return log_syntax_invalid_utf8(unit, LOG_ERR, filename, line, path);
394
395 if (flag & (PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE)) {
396 bool absolute;
397
398 absolute = path_is_absolute(path);
399
400 if (!absolute && (flag & PATH_CHECK_ABSOLUTE))
401 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
402 "%s= path is not absolute%s: %s",
403 lvalue, fatal ? "" : ", ignoring", path);
404
405 if (absolute && (flag & PATH_CHECK_RELATIVE))
406 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
407 "%s= path is absolute%s: %s",
408 lvalue, fatal ? "" : ", ignoring", path);
409 }
410
4ff361cc 411 path_simplify(path);
b47aa73a
ZJS
412
413 if (!path_is_valid(path))
414 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
415 "%s= path has invalid length (%zu bytes)%s.",
416 lvalue, strlen(path), fatal ? "" : ", ignoring");
417
418 if (!path_is_normalized(path))
419 return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
420 "%s= path is not normalized%s: %s",
421 lvalue, fatal ? "" : ", ignoring", path);
422
423 return 0;
424}
425
63f11e35 426char *path_startswith_full(const char *path, const char *prefix, bool accept_dot_dot) {
9eb977db
KS
427 assert(path);
428 assert(prefix);
429
0470289b
ZJS
430 /* Returns a pointer to the start of the first component after the parts matched by
431 * the prefix, iff
432 * - both paths are absolute or both paths are relative,
433 * and
434 * - each component in prefix in turn matches a component in path at the same position.
435 * An empty string will be returned when the prefix and path are equivalent.
436 *
437 * Returns NULL otherwise.
438 */
439
9eb977db 440 if ((path[0] == '/') != (prefix[0] == '/'))
424a19f8 441 return NULL;
9eb977db
KS
442
443 for (;;) {
63f11e35
YW
444 const char *p, *q;
445 int r, k;
9eb977db 446
63f11e35
YW
447 r = path_find_first_component(&path, accept_dot_dot, &p);
448 if (r < 0)
449 return NULL;
9eb977db 450
63f11e35
YW
451 k = path_find_first_component(&prefix, accept_dot_dot, &q);
452 if (k < 0)
424a19f8 453 return NULL;
9eb977db 454
63f11e35
YW
455 if (k == 0)
456 return (char*) (p ?: path);
9eb977db 457
63f11e35 458 if (r != k)
424a19f8 459 return NULL;
9eb977db 460
63f11e35 461 if (!strneq(p, q, r))
424a19f8 462 return NULL;
9eb977db
KS
463 }
464}
465
2230852b 466int path_compare(const char *a, const char *b) {
353df443 467 int r;
2230852b 468
10539677
LP
469 /* Order NULL before non-NULL */
470 r = CMP(!!a, !!b);
471 if (r != 0)
472 return r;
9eb977db 473
f21f31b2 474 /* A relative path and an absolute path must not compare as equal.
2230852b
MS
475 * Which one is sorted before the other does not really matter.
476 * Here a relative path is ordered before an absolute path. */
353df443
YW
477 r = CMP(path_is_absolute(a), path_is_absolute(b));
478 if (r != 0)
479 return r;
9eb977db
KS
480
481 for (;;) {
353df443
YW
482 const char *aa, *bb;
483 int j, k;
9eb977db 484
353df443
YW
485 j = path_find_first_component(&a, true, &aa);
486 k = path_find_first_component(&b, true, &bb);
9eb977db 487
353df443
YW
488 if (j < 0 || k < 0) {
489 /* When one of paths is invalid, order invalid path after valid one. */
490 r = CMP(j < 0, k < 0);
491 if (r != 0)
492 return r;
493
494 /* fallback to use strcmp() if both paths are invalid. */
495 return strcmp(a, b);
496 }
9eb977db 497
2230852b 498 /* Order prefixes first: "/foo" before "/foo/bar" */
353df443
YW
499 if (j == 0) {
500 if (k == 0)
501 return 0;
2230852b 502 return -1;
353df443
YW
503 }
504 if (k == 0)
2230852b 505 return 1;
9eb977db 506
2230852b 507 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
353df443
YW
508 r = memcmp(aa, bb, MIN(j, k));
509 if (r != 0)
510 return r;
9eb977db 511
2230852b 512 /* Sort "/foo/a" before "/foo/aaa" */
353df443
YW
513 r = CMP(j, k);
514 if (r != 0)
515 return r;
9eb977db
KS
516 }
517}
518
e3f791a2
ZJS
519bool path_equal_or_files_same(const char *a, const char *b, int flags) {
520 return path_equal(a, b) || files_same(a, b, flags) > 0;
c78e47a6
MS
521}
522
727e63e3
LB
523bool path_equal_filename(const char *a, const char *b) {
524 _cleanup_free_ char *a_basename = NULL, *b_basename = NULL;
525 int r;
526
527 assert(a);
528 assert(b);
529
530 r = path_extract_filename(a, &a_basename);
531 if (r < 0) {
532 log_debug_errno(r, "Failed to parse basename of %s: %m", a);
533 return false;
534 }
535 r = path_extract_filename(b, &b_basename);
536 if (r < 0) {
537 log_debug_errno(r, "Failed to parse basename of %s: %m", b);
538 return false;
539 }
540
541 return path_equal(a_basename, b_basename);
542}
543
7ae27680
LP
544char* path_extend_internal(char **x, ...) {
545 size_t sz, old_sz;
546 char *q, *nx;
cd8194a3
LP
547 const char *p;
548 va_list ap;
549 bool slash;
cd8194a3 550
652ef298
ZJS
551 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings end/begin
552 * already with one so that it is unnecessary. Note that slashes which are already duplicate won't be
553 * removed. The string returned is hence always equal to or longer than the sum of the lengths of each
554 * individual string.
cd8194a3 555 *
7ae27680
LP
556 * The first argument may be an already allocated string that is extended via realloc() if
557 * non-NULL. path_extend() and path_join() are macro wrappers around this function, making use of the
558 * first parameter to distinguish the two operations.
559 *
cd8194a3
LP
560 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of which some
561 * are optional.
562 *
563 * Examples:
564 *
62a85ee0
ZJS
565 * path_join("foo", "bar") → "foo/bar"
566 * path_join("foo/", "bar") → "foo/bar"
567 * path_join("", "foo", "", "bar", "") → "foo/bar" */
cd8194a3 568
7ae27680
LP
569 sz = old_sz = x ? strlen_ptr(*x) : 0;
570 va_start(ap, x);
571 while ((p = va_arg(ap, char*)) != POINTER_MAX) {
572 size_t add;
573
574 if (isempty(p))
575 continue;
576
577 add = 1 + strlen(p);
50fd596e
YW
578 if (sz > SIZE_MAX - add) { /* overflow check */
579 va_end(ap);
7ae27680 580 return NULL;
50fd596e 581 }
7ae27680
LP
582
583 sz += add;
584 }
cd8194a3
LP
585 va_end(ap);
586
7ae27680
LP
587 nx = realloc(x ? *x : NULL, GREEDY_ALLOC_ROUND_UP(sz+1));
588 if (!nx)
cd8194a3 589 return NULL;
7ae27680
LP
590 if (x)
591 *x = nx;
cd8194a3 592
7ae27680 593 if (old_sz > 0)
340cd6b6 594 slash = nx[old_sz-1] == '/';
7ae27680
LP
595 else {
596 nx[old_sz] = 0;
cd8194a3
LP
597 slash = true; /* no need to generate a slash anymore */
598 }
599
7ae27680
LP
600 q = nx + old_sz;
601
602 va_start(ap, x);
66032ef4 603 while ((p = va_arg(ap, char*)) != POINTER_MAX) {
652ef298 604 if (isempty(p))
cd8194a3
LP
605 continue;
606
607 if (!slash && p[0] != '/')
608 *(q++) = '/';
609
610 q = stpcpy(q, p);
611 slash = endswith(p, "/");
612 }
613 va_end(ap);
614
7ae27680 615 return nx;
cd8194a3
LP
616}
617
5ca9139a 618static int check_x_access(const char *path, int *ret_fd) {
ece852c8 619 _cleanup_close_ int fd = -1;
ece852c8 620 int r;
5ca9139a 621
888f65ac
YW
622 /* We need to use O_PATH because there may be executables for which we have only exec
623 * permissions, but not read (usually suid executables). */
624 fd = open(path, O_PATH|O_CLOEXEC);
625 if (fd < 0)
626 return -errno;
ece852c8 627
888f65ac
YW
628 r = fd_verify_regular(fd);
629 if (r < 0)
630 return r;
ece852c8 631
888f65ac 632 r = access_fd(fd, X_OK);
93413acd
YW
633 if (r == -ENOSYS) {
634 /* /proc is not mounted. Fallback to access(). */
635 if (access(path, X_OK) < 0)
636 return -errno;
637 } else if (r < 0)
888f65ac 638 return r;
ece852c8
YW
639
640 if (ret_fd)
641 *ret_fd = TAKE_FD(fd);
642
5ca9139a
ZJS
643 return 0;
644}
645
ded8039a
YW
646static int find_executable_impl(const char *name, const char *root, char **ret_filename, int *ret_fd) {
647 _cleanup_close_ int fd = -1;
648 _cleanup_free_ char *path_name = NULL;
649 int r;
85eca92e 650
c9d954b2 651 assert(name);
4087cb9e 652
ded8039a
YW
653 /* Function chase_symlinks() is invoked only when root is not NULL, as using it regardless of
654 * root value would alter the behavior of existing callers for example: /bin/sleep would become
655 * /usr/bin/sleep when find_executables is called. Hence, this function should be invoked when
656 * needed to avoid unforeseen regression or other complicated changes. */
657 if (root) {
658 r = chase_symlinks(name,
659 root,
660 CHASE_PREFIX_ROOT,
661 &path_name,
662 /* ret_fd= */ NULL); /* prefix root to name in case full paths are not specified */
663 if (r < 0)
664 return r;
36f4af05 665
ded8039a
YW
666 name = path_name;
667 }
36f4af05 668
ded8039a
YW
669 r = check_x_access(name, ret_fd ? &fd : NULL);
670 if (r < 0)
671 return r;
b972115c 672
ded8039a
YW
673 if (ret_filename) {
674 r = path_make_absolute_cwd(name, ret_filename);
5ca9139a
ZJS
675 if (r < 0)
676 return r;
ded8039a 677 }
5ca9139a 678
ded8039a
YW
679 if (ret_fd)
680 *ret_fd = TAKE_FD(fd);
c9d954b2 681
ded8039a
YW
682 return 0;
683}
5ca9139a 684
ded8039a
YW
685int find_executable_full(const char *name, const char *root, bool use_path_envvar, char **ret_filename, int *ret_fd) {
686 int last_error, r;
687 const char *p = NULL;
688
689 assert(name);
690
691 if (is_path(name))
692 return find_executable_impl(name, root, ret_filename, ret_fd);
c9d954b2 693
92673045
ZJS
694 if (use_path_envvar)
695 /* Plain getenv, not secure_getenv, because we want to actually allow the user to pick the
696 * binary. */
697 p = getenv("PATH");
85eca92e
LP
698 if (!p)
699 p = DEFAULT_PATH;
700
701 last_error = -ENOENT;
702
5ca9139a 703 /* Resolve a single-component name to a full path */
85eca92e 704 for (;;) {
4ede9802 705 _cleanup_free_ char *element = NULL;
85eca92e
LP
706
707 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
708 if (r < 0)
709 return r;
710 if (r == 0)
711 break;
712
0f474365
LP
713 if (!path_is_absolute(element))
714 continue;
715
4ede9802 716 if (!path_extend(&element, name))
85eca92e
LP
717 return -ENOMEM;
718
ded8039a 719 r = find_executable_impl(element, root, ret_filename, ret_fd);
ece852c8
YW
720 if (r < 0) {
721 /* PATH entries which we don't have access to are ignored, as per tradition. */
722 if (r != -EACCES)
723 last_error = r;
724 continue;
c9d954b2
ZJS
725 }
726
ece852c8 727 /* Found it! */
ece852c8 728 return 0;
c9d954b2 729 }
85eca92e
LP
730
731 return last_error;
c9d954b2 732}
8e184852 733
2ad8416d 734bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
0d5a24be 735 bool changed = false, originally_unset;
2ad8416d 736 const char* const* i;
8e184852 737
97f2d76d
TG
738 assert(timestamp);
739
234519ae 740 if (!paths)
4087cb9e 741 return false;
8e184852 742
0d5a24be
ZJS
743 originally_unset = *timestamp == 0;
744
4087cb9e 745 STRV_FOREACH(i, paths) {
8e184852 746 struct stat stats;
4087cb9e 747 usec_t u;
8e184852 748
4087cb9e 749 if (stat(*i, &stats) < 0)
8e184852
TG
750 continue;
751
4087cb9e
LP
752 u = timespec_load(&stats.st_mtim);
753
0d5a24be 754 /* check first */
4087cb9e 755 if (*timestamp >= u)
8e184852
TG
756 continue;
757
0d5a24be 758 log_debug(originally_unset ? "Loaded timestamp for '%s'." : "Timestamp of '%s' changed.", *i);
8e184852
TG
759
760 /* update timestamp */
4087cb9e
LP
761 if (update) {
762 *timestamp = u;
763 changed = true;
764 } else
765 return true;
8e184852 766 }
4087cb9e 767
8e184852
TG
768 return changed;
769}
eb66db55 770
f7bc0c32 771static int executable_is_good(const char *executable) {
571d0134 772 _cleanup_free_ char *p = NULL, *d = NULL;
571d0134 773 int r;
eb66db55 774
f7bc0c32 775 r = find_executable(executable, &p);
85eca92e
LP
776 if (r == -ENOENT)
777 return 0;
571d0134
LP
778 if (r < 0)
779 return r;
780
f7bc0c32 781 /* An fsck that is linked to /bin/true is a non-existent fsck */
571d0134
LP
782
783 r = readlink_malloc(p, &d);
85eca92e
LP
784 if (r == -EINVAL) /* not a symlink */
785 return 1;
786 if (r < 0)
787 return r;
571d0134 788
3ae5990c
ZJS
789 return !PATH_IN_SET(d, "true"
790 "/bin/true",
791 "/usr/bin/true",
792 "/dev/null");
eb66db55 793}
1d13f648 794
5bcd08db
LP
795int fsck_exists(const char *fstype) {
796 const char *checker;
797
85eca92e 798 assert(fstype);
5bcd08db 799
85eca92e
LP
800 if (streq(fstype, "auto"))
801 return -EINVAL;
802
803 checker = strjoina("fsck.", fstype);
f7bc0c32 804 return executable_is_good(checker);
5bcd08db
LP
805}
806
5f311f8c
LP
807char* dirname_malloc(const char *path) {
808 char *d, *dir, *dir2;
809
810 assert(path);
811
812 d = strdup(path);
813 if (!d)
814 return NULL;
815
816 dir = dirname(d);
817 assert(dir);
818
819 if (dir == d)
820 return d;
821
822 dir2 = strdup(dir);
823 free(d);
824
825 return dir2;
826}
bb15fafe 827
0ee54dd4
YW
828static const char *skip_slash_or_dot(const char *p) {
829 for (; !isempty(p); p++) {
830 if (*p == '/')
831 continue;
832 if (startswith(p, "./")) {
833 p++;
834 continue;
835 }
836 break;
837 }
838 return p;
839}
840
841int path_find_first_component(const char **p, bool accept_dot_dot, const char **ret) {
842 const char *q, *first, *end_first, *next;
843 size_t len;
844
845 assert(p);
846
847 /* When a path is input, then returns the pointer to the first component and its length, and
848 * move the input pointer to the next component or nul. This skips both over any '/'
849 * immediately *before* and *after* the first component before returning.
850 *
851 * Examples
852 * Input: p: "//.//aaa///bbbbb/cc"
853 * Output: p: "bbbbb///cc"
854 * ret: "aaa///bbbbb/cc"
855 * return value: 3 (== strlen("aaa"))
856 *
857 * Input: p: "aaa//"
858 * Output: p: (pointer to NUL)
859 * ret: "aaa//"
860 * return value: 3 (== strlen("aaa"))
861 *
862 * Input: p: "/", ".", ""
863 * Output: p: (pointer to NUL)
864 * ret: NULL
865 * return value: 0
866 *
867 * Input: p: NULL
868 * Output: p: NULL
869 * ret: NULL
870 * return value: 0
871 *
872 * Input: p: "(too long component)"
873 * Output: return value: -EINVAL
874 *
875 * (when accept_dot_dot is false)
876 * Input: p: "//..//aaa///bbbbb/cc"
877 * Output: return value: -EINVAL
878 */
879
880 q = *p;
881
882 first = skip_slash_or_dot(q);
883 if (isempty(first)) {
884 *p = first;
885 if (ret)
886 *ret = NULL;
887 return 0;
888 }
889 if (streq(first, ".")) {
890 *p = first + 1;
891 if (ret)
892 *ret = NULL;
893 return 0;
894 }
895
896 end_first = strchrnul(first, '/');
897 len = end_first - first;
898
899 if (len > NAME_MAX)
900 return -EINVAL;
901 if (!accept_dot_dot && len == 2 && first[0] == '.' && first[1] == '.')
902 return -EINVAL;
903
904 next = skip_slash_or_dot(end_first);
905
906 *p = next + streq(next, ".");
907 if (ret)
908 *ret = first;
909 return len;
910}
911
484cd43c
YW
912static const char *skip_slash_or_dot_backward(const char *path, const char *q) {
913 assert(path);
914
915 for (; q >= path; q--) {
916 if (*q == '/')
917 continue;
918 if (q > path && strneq(q - 1, "/.", 2))
919 continue;
920 break;
921 }
922 return q;
923}
924
925int path_find_last_component(const char *path, bool accept_dot_dot, const char **next, const char **ret) {
926 const char *q, *last_end, *last_begin;
927 size_t len;
928
929 /* Similar to path_find_first_component(), but search components from the end.
930 *
931 * Examples
932 * Input: path: "//.//aaa///bbbbb/cc//././"
933 * next: NULL
934 * Output: next: "/cc//././"
935 * ret: "cc//././"
936 * return value: 2 (== strlen("cc"))
937 *
938 * Input: path: "//.//aaa///bbbbb/cc//././"
939 * next: "/cc//././"
940 * Output: next: "///bbbbb/cc//././"
941 * ret: "bbbbb/cc//././"
942 * return value: 5 (== strlen("bbbbb"))
943 *
944 * Input: path: "/", ".", "", or NULL
945 * Output: next: equivalent to path
946 * ret: NULL
947 * return value: 0
948 *
949 * Input: path: "(too long component)"
950 * Output: return value: -EINVAL
951 *
952 * (when accept_dot_dot is false)
953 * Input: path: "//..//aaa///bbbbb/cc/..//"
954 * Output: return value: -EINVAL
955 */
956
957 if (isempty(path)) {
958 if (next)
959 *next = path;
960 if (ret)
961 *ret = NULL;
962 return 0;
963 }
964
965 if (next && *next) {
966 if (*next < path || *next > path + strlen(path))
967 return -EINVAL;
968 if (*next == path) {
969 if (ret)
970 *ret = NULL;
971 return 0;
972 }
973 if (!IN_SET(**next, '\0', '/'))
974 return -EINVAL;
975 q = *next - 1;
976 } else
977 q = path + strlen(path) - 1;
978
979 q = skip_slash_or_dot_backward(path, q);
980 if ((q < path) || /* the root directory */
981 (q == path && *q == '.')) { /* path is "." or "./" */
982 if (next)
983 *next = path;
984 if (ret)
985 *ret = NULL;
986 return 0;
987 }
988
989 last_end = q + 1;
990
991 while (q >= path && *q != '/')
992 q--;
993
994 last_begin = q + 1;
995 len = last_end - last_begin;
996
997 if (len > NAME_MAX)
998 return -EINVAL;
999 if (!accept_dot_dot && len == 2 && strneq(last_begin, "..", 2))
1000 return -EINVAL;
1001
1002 if (next) {
1003 q = skip_slash_or_dot_backward(path, q);
1004 if (q < path)
1005 *next = path;
1006 else
1007 *next = q + 1;
1008 }
1009
1010 if (ret)
1011 *ret = last_begin;
1012 return len;
1013}
1014
b12d25a8 1015const char *last_path_component(const char *path) {
8460289f
LP
1016
1017 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
1018 *
b12d25a8
ZJS
1019 * a/b/c → c
1020 * a/b/c/ → c/
8460289f
LP
1021 * x → x
1022 * x/ → x/
1023 * /y → y
1024 * /y/ → y/
b12d25a8
ZJS
1025 * / → /
1026 * // → /
1027 * /foo/a → a
1028 * /foo/a/ → a/
8460289f
LP
1029 *
1030 * Also, the empty string is mapped to itself.
1031 *
1032 * This is different than basename(), which returns "" when a trailing slash is present.
3cdcbdd3
LP
1033 *
1034 * This always succeeds (except if you pass NULL in which case it returns NULL, too).
b12d25a8
ZJS
1035 */
1036
1037 unsigned l, k;
1038
77e0a1b5
LP
1039 if (!path)
1040 return NULL;
1041
b12d25a8 1042 l = k = strlen(path);
69f9ccf1
ZJS
1043 if (l == 0) /* special case — an empty string */
1044 return path;
1045
b12d25a8
ZJS
1046 while (k > 0 && path[k-1] == '/')
1047 k--;
1048
1049 if (k == 0) /* the root directory */
1050 return path + l - 1;
1051
1052 while (k > 0 && path[k-1] != '/')
1053 k--;
1054
1055 return path + k;
1056}
1057
01950464 1058int path_extract_filename(const char *path, char **ret) {
a60c8eee 1059 _cleanup_free_ char *a = NULL;
01950464
YW
1060 const char *c, *next = NULL;
1061 int r;
a60c8eee
LP
1062
1063 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
ee277c6b
LP
1064 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing
1065 * slashes. Returns:
1066 *
01950464
YW
1067 * -EINVAL → if the path is not valid
1068 * -EADDRNOTAVAIL → if only a directory was specified, but no filename, i.e. the root dir
1069 * itself or "." is specified
ee277c6b
LP
1070 * -ENOMEM → no memory
1071 *
01950464
YW
1072 * Returns >= 0 on success. If the input path has a trailing slash, returns O_DIRECTORY, to
1073 * indicate the referenced file must be a directory.
ee277c6b
LP
1074 *
1075 * This function guarantees to return a fully valid filename, i.e. one that passes
1076 * filename_is_valid() – this means "." and ".." are not accepted. */
a60c8eee 1077
01950464 1078 if (!path_is_valid(path))
a60c8eee
LP
1079 return -EINVAL;
1080
01950464
YW
1081 r = path_find_last_component(path, false, &next, &c);
1082 if (r < 0)
1083 return r;
1084 if (r == 0) /* root directory */
3cdcbdd3 1085 return -EADDRNOTAVAIL;
a60c8eee 1086
01950464 1087 a = strndup(c, r);
a60c8eee
LP
1088 if (!a)
1089 return -ENOMEM;
1090
a60c8eee 1091 *ret = TAKE_PTR(a);
01950464 1092 return strlen(c) > (size_t)r ? O_DIRECTORY : 0;
a60c8eee
LP
1093}
1094
01950464 1095int path_extract_directory(const char *path, char **ret) {
8dcb891c 1096 _cleanup_free_ char *a = NULL;
01950464
YW
1097 const char *c, *next = NULL;
1098 int r;
8dcb891c
LP
1099
1100 /* The inverse of path_extract_filename(), i.e. returns the directory path prefix. Returns:
1101 *
01950464 1102 * -EINVAL → if the path is not valid
8dcb891c 1103 * -EDESTADDRREQ → if no directory was specified in the passed in path, i.e. only a filename was passed
01950464
YW
1104 * -EADDRNOTAVAIL → if the passed in parameter had no filename but did have a directory, i.e.
1105 * the root dir itself or "." was specified
8dcb891c
LP
1106 * -ENOMEM → no memory (surprise!)
1107 *
1108 * This function guarantees to return a fully valid path, i.e. one that passes path_is_valid().
1109 */
1110
01950464
YW
1111 r = path_find_last_component(path, false, &next, &c);
1112 if (r < 0)
1113 return r;
1114 if (r == 0) /* empty or root */
1115 return isempty(path) ? -EINVAL : -EADDRNOTAVAIL;
1116 if (next == path) {
1117 if (*path != '/') /* filename only */
1118 return -EDESTADDRREQ;
1119
1120 a = strdup("/");
1121 if (!a)
1122 return -ENOMEM;
1123 *ret = TAKE_PTR(a);
1124 return 0;
1125 }
8dcb891c 1126
01950464 1127 a = strndup(path, next - path);
8dcb891c
LP
1128 if (!a)
1129 return -ENOMEM;
1130
4ff361cc 1131 path_simplify(a);
01950464 1132
8dcb891c
LP
1133 if (!path_is_valid(a))
1134 return -EINVAL;
1135
1136 *ret = TAKE_PTR(a);
1137 return 0;
1138}
1139
bb15fafe
LP
1140bool filename_is_valid(const char *p) {
1141 const char *e;
1142
1143 if (isempty(p))
1144 return false;
1145
49bfc877 1146 if (dot_or_dot_dot(p))
bb15fafe
LP
1147 return false;
1148
1149 e = strchrnul(p, '/');
1150 if (*e != 0)
1151 return false;
1152
2ef2376d 1153 if (e - p > NAME_MAX) /* NAME_MAX is counted *without* the trailing NUL byte */
bb15fafe
LP
1154 return false;
1155
1156 return true;
1157}
1158
32df2e14 1159bool path_is_valid_full(const char *p, bool accept_dot_dot) {
bb15fafe
LP
1160 if (isempty(p))
1161 return false;
1162
2ef2376d 1163 for (const char *e = p;;) {
66368835
YW
1164 int r;
1165
32df2e14 1166 r = path_find_first_component(&e, accept_dot_dot, NULL);
66368835
YW
1167 if (r < 0)
1168 return false;
49bfc877 1169
2ef2376d
LP
1170 if (e - p >= PATH_MAX) /* Already reached the maximum length for a path? (PATH_MAX is counted
1171 * *with* the trailing NUL byte) */
1172 return false;
1173 if (*e == 0) /* End of string? Yay! */
1174 return true;
2ef2376d 1175 }
656552eb
LP
1176}
1177
1178bool path_is_normalized(const char *p) {
0b869625 1179 if (!path_is_safe(p))
bb15fafe
LP
1180 return false;
1181
0b869625 1182 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
bb15fafe
LP
1183 return false;
1184
1185 if (strstr(p, "//"))
1186 return false;
1187
1188 return true;
1189}
a0956174
LP
1190
1191char *file_in_same_dir(const char *path, const char *filename) {
1192 char *e, *ret;
1193 size_t k;
1194
1195 assert(path);
1196 assert(filename);
1197
1198 /* This removes the last component of path and appends
1199 * filename, unless the latter is absolute anyway or the
1200 * former isn't */
1201
1202 if (path_is_absolute(filename))
1203 return strdup(filename);
1204
1205 e = strrchr(path, '/');
1206 if (!e)
1207 return strdup(filename);
1208
1209 k = strlen(filename);
1210 ret = new(char, (e + 1 - path) + k + 1);
1211 if (!ret)
1212 return NULL;
1213
1214 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
1215 return ret;
1216}
1217
55cdd057
ZJS
1218bool hidden_or_backup_file(const char *filename) {
1219 const char *p;
a0956174 1220
a0956174
LP
1221 assert(filename);
1222
55cdd057
ZJS
1223 if (filename[0] == '.' ||
1224 streq(filename, "lost+found") ||
1225 streq(filename, "aquota.user") ||
1226 streq(filename, "aquota.group") ||
1227 endswith(filename, "~"))
a0956174
LP
1228 return true;
1229
55cdd057
ZJS
1230 p = strrchr(filename, '.');
1231 if (!p)
1232 return false;
1233
941060bf
LP
1234 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
1235 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
1236 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
1237 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
1238 * string. Specifically: there's now:
1239 *
1240 * The generic suffixes "~" and ".bak" for backup files
1241 * The generic prefix "." for hidden files
1242 *
94a0ef6e
ZJS
1243 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
1244 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
941060bf
LP
1245 */
1246
55cdd057
ZJS
1247 return STR_IN_SET(p + 1,
1248 "rpmnew",
1249 "rpmsave",
1250 "rpmorig",
1251 "dpkg-old",
1252 "dpkg-new",
1253 "dpkg-tmp",
1254 "dpkg-dist",
1255 "dpkg-bak",
1256 "dpkg-backup",
1257 "dpkg-remove",
1258 "ucf-new",
1259 "ucf-old",
1260 "ucf-dist",
941060bf 1261 "swp",
94a0ef6e
ZJS
1262 "bak",
1263 "old",
1264 "new");
a0956174
LP
1265}
1266
1267bool is_device_path(const char *path) {
1268
bae47ba7 1269 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
a0956174 1270
bae47ba7 1271 return PATH_STARTSWITH_SET(path, "/dev/", "/sys/");
3ccb8862
ZJS
1272}
1273
57e84e75
LP
1274bool valid_device_node_path(const char *path) {
1275
1276 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
1277 * actual device node. */
1278
1279 if (!PATH_STARTSWITH_SET(path, "/dev/", "/run/systemd/inaccessible/"))
1280 return false;
1281
1282 if (endswith(path, "/")) /* can't be a device node if it ends in a slash */
1283 return false;
1284
1285 return path_is_normalized(path);
1286}
1287
1288bool valid_device_allow_pattern(const char *path) {
1289 assert(path);
1290
1291 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
1292 * accept it */
1293
49fe5c09 1294 if (STARTSWITH_SET(path, "block-", "char-"))
57e84e75
LP
1295 return true;
1296
1297 return valid_device_node_path(path);
a0956174 1298}
5a46d55f
ZJS
1299
1300int systemd_installation_has_version(const char *root, unsigned minimal_version) {
1301 const char *pattern;
1302 int r;
1303
1304 /* Try to guess if systemd installation is later than the specified version. This
1305 * is hacky and likely to yield false negatives, particularly if the installation
1306 * is non-standard. False positives should be relatively rare.
1307 */
1308
1309 NULSTR_FOREACH(pattern,
1310 /* /lib works for systems without usr-merge, and for systems with a sane
1311 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
1312 * for Gentoo which does a merge without making /lib a symlink.
1313 */
1314 "lib/systemd/libsystemd-shared-*.so\0"
28faeda4
LP
1315 "lib64/systemd/libsystemd-shared-*.so\0"
1316 "usr/lib/systemd/libsystemd-shared-*.so\0"
1317 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
5a46d55f
ZJS
1318
1319 _cleanup_strv_free_ char **names = NULL;
1320 _cleanup_free_ char *path = NULL;
1321 char *c, **name;
1322
c6134d3e 1323 path = path_join(root, pattern);
5a46d55f
ZJS
1324 if (!path)
1325 return -ENOMEM;
1326
544e146b 1327 r = glob_extend(&names, path, 0);
5a46d55f
ZJS
1328 if (r == -ENOENT)
1329 continue;
1330 if (r < 0)
1331 return r;
1332
dcd6361e 1333 assert_se(c = endswith(path, "*.so"));
5a46d55f
ZJS
1334 *c = '\0'; /* truncate the glob part */
1335
1336 STRV_FOREACH(name, names) {
1337 /* This is most likely to run only once, hence let's not optimize anything. */
1338 char *t, *t2;
1339 unsigned version;
1340
1341 t = startswith(*name, path);
1342 if (!t)
1343 continue;
1344
1345 t2 = endswith(t, ".so");
1346 if (!t2)
1347 continue;
1348
1349 t2[0] = '\0'; /* truncate the suffix */
1350
1351 r = safe_atou(t, &version);
1352 if (r < 0) {
1353 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
1354 continue;
1355 }
1356
1357 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1358 *name, version,
1359 version >= minimal_version ? "OK" : "too old");
1360 if (version >= minimal_version)
1361 return true;
1362 }
1363 }
1364
1365 return false;
1366}
49bfc877
LP
1367
1368bool dot_or_dot_dot(const char *path) {
1369 if (!path)
1370 return false;
1371 if (path[0] != '.')
1372 return false;
1373 if (path[1] == 0)
1374 return true;
1375 if (path[1] != '.')
1376 return false;
1377
1378 return path[2] == 0;
1379}
57ea45e1 1380
15bac3e8 1381bool empty_or_root(const char *path) {
57ea45e1
LP
1382
1383 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1384 * i.e. either / or NULL or the empty string or any equivalent. */
1385
15bac3e8 1386 if (isempty(path))
57ea45e1
LP
1387 return true;
1388
15bac3e8 1389 return path_equal(path, "/");
57ea45e1 1390}
3841fee8
LP
1391
1392bool path_strv_contains(char **l, const char *path) {
1393 char **i;
1394
1395 STRV_FOREACH(i, l)
1396 if (path_equal(*i, path))
1397 return true;
1398
1399 return false;
1400}
de46b2be
TM
1401
1402bool prefixed_path_strv_contains(char **l, const char *path) {
1403 char **i, *j;
1404
1405 STRV_FOREACH(i, l) {
1406 j = *i;
1407 if (*j == '-')
1408 j++;
1409 if (*j == '+')
1410 j++;
1411 if (path_equal(j, path))
1412 return true;
1413 }
1414
1415 return false;
1416}