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