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