chiark / gitweb /
fs-util: introduce fchmod_and_chown()
[elogind.git] / src / basic / fs-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   This file is part of systemd.
4
5   Copyright 2010 Lennart Poettering
6 ***/
7
8 #include <errno.h>
9 #include <stddef.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <sys/stat.h>
14 #include <linux/magic.h>
15 #include <time.h>
16 #include <unistd.h>
17
18 #include "alloc-util.h"
19 #include "dirent-util.h"
20 #include "fd-util.h"
21 #include "fileio.h"
22 #include "fs-util.h"
23 //#include "log.h"
24 //#include "macro.h"
25 //#include "missing.h"
26 #include "mkdir.h"
27 #include "parse-util.h"
28 #include "path-util.h"
29 //#include "process-util.h"
30 #include "stat-util.h"
31 #include "stdio-util.h"
32 #include "string-util.h"
33 #include "strv.h"
34 //#include "time-util.h"
35 #include "user-util.h"
36 #include "util.h"
37
38 /// Additional includes needed by elogind
39 #include "process-util.h"
40
41 int unlink_noerrno(const char *path) {
42         PROTECT_ERRNO;
43         int r;
44
45         r = unlink(path);
46         if (r < 0)
47                 return -errno;
48
49         return 0;
50 }
51
52 #if 0 /// UNNEEDED by elogind
53 int rmdir_parents(const char *path, const char *stop) {
54         size_t l;
55         int r = 0;
56
57         assert(path);
58         assert(stop);
59
60         l = strlen(path);
61
62         /* Skip trailing slashes */
63         while (l > 0 && path[l-1] == '/')
64                 l--;
65
66         while (l > 0) {
67                 char *t;
68
69                 /* Skip last component */
70                 while (l > 0 && path[l-1] != '/')
71                         l--;
72
73                 /* Skip trailing slashes */
74                 while (l > 0 && path[l-1] == '/')
75                         l--;
76
77                 if (l <= 0)
78                         break;
79
80                 t = strndup(path, l);
81                 if (!t)
82                         return -ENOMEM;
83
84                 if (path_startswith(stop, t)) {
85                         free(t);
86                         return 0;
87                 }
88
89                 r = rmdir(t);
90                 free(t);
91
92                 if (r < 0)
93                         if (errno != ENOENT)
94                                 return -errno;
95         }
96
97         return 0;
98 }
99
100 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
101         struct stat buf;
102         int ret;
103
104         ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
105         if (ret >= 0)
106                 return 0;
107
108         /* renameat2() exists since Linux 3.15, btrfs added support for it later.
109          * If it is not implemented, fallback to another method. */
110         if (!IN_SET(errno, EINVAL, ENOSYS))
111                 return -errno;
112
113         /* The link()/unlink() fallback does not work on directories. But
114          * renameat() without RENAME_NOREPLACE gives the same semantics on
115          * directories, except when newpath is an *empty* directory. This is
116          * good enough. */
117         ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
118         if (ret >= 0 && S_ISDIR(buf.st_mode)) {
119                 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
120                 return ret >= 0 ? 0 : -errno;
121         }
122
123         /* If it is not a directory, use the link()/unlink() fallback. */
124         ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
125         if (ret < 0)
126                 return -errno;
127
128         ret = unlinkat(olddirfd, oldpath, 0);
129         if (ret < 0) {
130                 /* backup errno before the following unlinkat() alters it */
131                 ret = errno;
132                 (void) unlinkat(newdirfd, newpath, 0);
133                 errno = ret;
134                 return -errno;
135         }
136
137         return 0;
138 }
139 #endif // 0
140
141 int readlinkat_malloc(int fd, const char *p, char **ret) {
142         size_t l = 100;
143         int r;
144
145         assert(p);
146         assert(ret);
147
148         for (;;) {
149                 char *c;
150                 ssize_t n;
151
152                 c = new(char, l);
153                 if (!c)
154                         return -ENOMEM;
155
156                 n = readlinkat(fd, p, c, l-1);
157                 if (n < 0) {
158                         r = -errno;
159                         free(c);
160                         return r;
161                 }
162
163                 if ((size_t) n < l-1) {
164                         c[n] = 0;
165                         *ret = c;
166                         return 0;
167                 }
168
169                 free(c);
170                 l *= 2;
171         }
172 }
173
174 int readlink_malloc(const char *p, char **ret) {
175         return readlinkat_malloc(AT_FDCWD, p, ret);
176 }
177
178 #if 0 /// UNNEEDED by elogind
179 int readlink_value(const char *p, char **ret) {
180         _cleanup_free_ char *link = NULL;
181         char *value;
182         int r;
183
184         r = readlink_malloc(p, &link);
185         if (r < 0)
186                 return r;
187
188         value = basename(link);
189         if (!value)
190                 return -ENOENT;
191
192         value = strdup(value);
193         if (!value)
194                 return -ENOMEM;
195
196         *ret = value;
197
198         return 0;
199 }
200 #endif // 0
201
202 int readlink_and_make_absolute(const char *p, char **r) {
203         _cleanup_free_ char *target = NULL;
204         char *k;
205         int j;
206
207         assert(p);
208         assert(r);
209
210         j = readlink_malloc(p, &target);
211         if (j < 0)
212                 return j;
213
214         k = file_in_same_dir(p, target);
215         if (!k)
216                 return -ENOMEM;
217
218         *r = k;
219         return 0;
220 }
221
222 #if 0 /// UNNEEDED by elogind
223 #endif // 0
224 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
225         assert(path);
226
227         /* Under the assumption that we are running privileged we
228          * first change the access mode and only then hand out
229          * ownership to avoid a window where access is too open. */
230
231         if (mode != MODE_INVALID)
232                 if (chmod(path, mode) < 0)
233                         return -errno;
234
235         if (uid != UID_INVALID || gid != GID_INVALID)
236                 if (chown(path, uid, gid) < 0)
237                         return -errno;
238
239         return 0;
240 }
241
242 int fchmod_and_chown(int fd, mode_t mode, uid_t uid, gid_t gid) {
243         /* Under the assumption that we are running privileged we
244          * first change the access mode and only then hand out
245          * ownership to avoid a window where access is too open. */
246
247         if (mode != MODE_INVALID)
248                 if (fchmod(fd, mode) < 0)
249                         return -errno;
250
251         if (uid != UID_INVALID || gid != GID_INVALID)
252                 if (fchown(fd, uid, gid) < 0)
253                         return -errno;
254
255         return 0;
256 }
257
258 int fchmod_umask(int fd, mode_t m) {
259         mode_t u;
260         int r;
261
262         u = umask(0777);
263         r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
264         umask(u);
265
266         return r;
267 }
268
269 int fchmod_opath(int fd, mode_t m) {
270         char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
271
272         /* This function operates also on fd that might have been opened with
273          * O_PATH. Indeed fchmodat() doesn't have the AT_EMPTY_PATH flag like
274          * fchownat() does. */
275
276         xsprintf(procfs_path, "/proc/self/fd/%i", fd);
277
278         if (chmod(procfs_path, m) < 0)
279                 return -errno;
280
281         return 0;
282 }
283
284 int fd_warn_permissions(const char *path, int fd) {
285         struct stat st;
286
287         if (fstat(fd, &st) < 0)
288                 return -errno;
289
290         if (st.st_mode & 0111)
291                 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
292
293         if (st.st_mode & 0002)
294                 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
295
296         if (getpid_cached() == 1 && (st.st_mode & 0044) != 0044)
297                 log_warning("Configuration file %s is marked world-inaccessible. This has no effect as configuration data is accessible via APIs without restrictions. Proceeding anyway.", path);
298
299         return 0;
300 }
301
302 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
303         char fdpath[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
304         _cleanup_close_ int fd = -1;
305         int r, ret = 0;
306
307         assert(path);
308
309         /* Note that touch_file() does not follow symlinks: if invoked on an existing symlink, then it is the symlink
310          * itself which is updated, not its target
311          *
312          * Returns the first error we encounter, but tries to apply as much as possible. */
313
314         if (parents)
315                 (void) mkdir_parents(path, 0755);
316
317         /* Initially, we try to open the node with O_PATH, so that we get a reference to the node. This is useful in
318          * case the path refers to an existing device or socket node, as we can open it successfully in all cases, and
319          * won't trigger any driver magic or so. */
320         fd = open(path, O_PATH|O_CLOEXEC|O_NOFOLLOW);
321         if (fd < 0) {
322                 if (errno != ENOENT)
323                         return -errno;
324
325                 /* if the node doesn't exist yet, we create it, but with O_EXCL, so that we only create a regular file
326                  * here, and nothing else */
327                 fd = open(path, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC, IN_SET(mode, 0, MODE_INVALID) ? 0644 : mode);
328                 if (fd < 0)
329                         return -errno;
330         }
331
332         /* Let's make a path from the fd, and operate on that. With this logic, we can adjust the access mode,
333          * ownership and time of the file node in all cases, even if the fd refers to an O_PATH object â€” which is
334          * something fchown(), fchmod(), futimensat() don't allow. */
335         xsprintf(fdpath, "/proc/self/fd/%i", fd);
336
337         if (mode != MODE_INVALID)
338                 if (chmod(fdpath, mode) < 0)
339                         ret = -errno;
340
341         if (uid_is_valid(uid) || gid_is_valid(gid))
342                 if (chown(fdpath, uid, gid) < 0 && ret >= 0)
343                         ret = -errno;
344
345         if (stamp != USEC_INFINITY) {
346                 struct timespec ts[2];
347
348                 timespec_store(&ts[0], stamp);
349                 ts[1] = ts[0];
350                 r = utimensat(AT_FDCWD, fdpath, ts, 0);
351         } else
352                 r = utimensat(AT_FDCWD, fdpath, NULL, 0);
353         if (r < 0 && ret >= 0)
354                 return -errno;
355
356         return ret;
357 }
358
359 int touch(const char *path) {
360         return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
361 }
362
363 #if 0 /// UNNEEDED by elogind
364 int symlink_idempotent(const char *from, const char *to) {
365         int r;
366
367         assert(from);
368         assert(to);
369
370         if (symlink(from, to) < 0) {
371                 _cleanup_free_ char *p = NULL;
372
373                 if (errno != EEXIST)
374                         return -errno;
375
376                 r = readlink_malloc(to, &p);
377                 if (r == -EINVAL) /* Not a symlink? In that case return the original error we encountered: -EEXIST */
378                         return -EEXIST;
379                 if (r < 0) /* Any other error? In that case propagate it as is */
380                         return r;
381
382                 if (!streq(p, from)) /* Not the symlink we want it to be? In that case, propagate the original -EEXIST */
383                         return -EEXIST;
384         }
385
386         return 0;
387 }
388
389 int symlink_atomic(const char *from, const char *to) {
390         _cleanup_free_ char *t = NULL;
391         int r;
392
393         assert(from);
394         assert(to);
395
396         r = tempfn_random(to, NULL, &t);
397         if (r < 0)
398                 return r;
399
400         if (symlink(from, t) < 0)
401                 return -errno;
402
403         if (rename(t, to) < 0) {
404                 unlink_noerrno(t);
405                 return -errno;
406         }
407
408         return 0;
409 }
410
411 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
412         _cleanup_free_ char *t = NULL;
413         int r;
414
415         assert(path);
416
417         r = tempfn_random(path, NULL, &t);
418         if (r < 0)
419                 return r;
420
421         if (mknod(t, mode, dev) < 0)
422                 return -errno;
423
424         if (rename(t, path) < 0) {
425                 unlink_noerrno(t);
426                 return -errno;
427         }
428
429         return 0;
430 }
431
432 int mkfifo_atomic(const char *path, mode_t mode) {
433         _cleanup_free_ char *t = NULL;
434         int r;
435
436         assert(path);
437
438         r = tempfn_random(path, NULL, &t);
439         if (r < 0)
440                 return r;
441
442         if (mkfifo(t, mode) < 0)
443                 return -errno;
444
445         if (rename(t, path) < 0) {
446                 unlink_noerrno(t);
447                 return -errno;
448         }
449
450         return 0;
451 }
452 #endif // 0
453
454 int get_files_in_directory(const char *path, char ***list) {
455         _cleanup_closedir_ DIR *d = NULL;
456         struct dirent *de;
457         size_t bufsize = 0, n = 0;
458         _cleanup_strv_free_ char **l = NULL;
459
460         assert(path);
461
462         /* Returns all files in a directory in *list, and the number
463          * of files as return value. If list is NULL returns only the
464          * number. */
465
466         d = opendir(path);
467         if (!d)
468                 return -errno;
469
470         FOREACH_DIRENT_ALL(de, d, return -errno) {
471                 dirent_ensure_type(d, de);
472
473                 if (!dirent_is_file(de))
474                         continue;
475
476                 if (list) {
477                         /* one extra slot is needed for the terminating NULL */
478                         if (!GREEDY_REALLOC(l, bufsize, n + 2))
479                                 return -ENOMEM;
480
481                         l[n] = strdup(de->d_name);
482                         if (!l[n])
483                                 return -ENOMEM;
484
485                         l[++n] = NULL;
486                 } else
487                         n++;
488         }
489
490         if (list)
491                 *list = TAKE_PTR(l);
492
493         return n;
494 }
495
496 static int getenv_tmp_dir(const char **ret_path) {
497         const char *n;
498         int r, ret = 0;
499
500         assert(ret_path);
501
502         /* We use the same order of environment variables python uses in tempfile.gettempdir():
503          * https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir */
504         FOREACH_STRING(n, "TMPDIR", "TEMP", "TMP") {
505                 const char *e;
506
507                 e = secure_getenv(n);
508                 if (!e)
509                         continue;
510                 if (!path_is_absolute(e)) {
511                         r = -ENOTDIR;
512                         goto next;
513                 }
514                 if (!path_is_normalized(e)) {
515                         r = -EPERM;
516                         goto next;
517                 }
518
519                 r = is_dir(e, true);
520                 if (r < 0)
521                         goto next;
522                 if (r == 0) {
523                         r = -ENOTDIR;
524                         goto next;
525                 }
526
527                 *ret_path = e;
528                 return 1;
529
530         next:
531                 /* Remember first error, to make this more debuggable */
532                 if (ret >= 0)
533                         ret = r;
534         }
535
536         if (ret < 0)
537                 return ret;
538
539         *ret_path = NULL;
540         return ret;
541 }
542
543 static int tmp_dir_internal(const char *def, const char **ret) {
544         const char *e;
545         int r, k;
546
547         assert(def);
548         assert(ret);
549
550         r = getenv_tmp_dir(&e);
551         if (r > 0) {
552                 *ret = e;
553                 return 0;
554         }
555
556         k = is_dir(def, true);
557         if (k == 0)
558                 k = -ENOTDIR;
559         if (k < 0)
560                 return r < 0 ? r : k;
561
562         *ret = def;
563         return 0;
564 }
565
566 #if 0 /// UNNEEDED by elogind
567 int var_tmp_dir(const char **ret) {
568
569         /* Returns the location for "larger" temporary files, that is backed by physical storage if available, and thus
570          * even might survive a boot: /var/tmp. If $TMPDIR (or related environment variables) are set, its value is
571          * returned preferably however. Note that both this function and tmp_dir() below are affected by $TMPDIR,
572          * making it a variable that overrides all temporary file storage locations. */
573
574         return tmp_dir_internal("/var/tmp", ret);
575 }
576 #endif // 0
577
578 int tmp_dir(const char **ret) {
579
580         /* Similar to var_tmp_dir() above, but returns the location for "smaller" temporary files, which is usually
581          * backed by an in-memory file system: /tmp. */
582
583         return tmp_dir_internal("/tmp", ret);
584 }
585
586 int unlink_or_warn(const char *filename) {
587         if (unlink(filename) < 0 && errno != ENOENT)
588                 /* If the file doesn't exist and the fs simply was read-only (in which
589                  * case unlink() returns EROFS even if the file doesn't exist), don't
590                  * complain */
591                 if (errno != EROFS || access(filename, F_OK) >= 0)
592                         return log_error_errno(errno, "Failed to remove \"%s\": %m", filename);
593
594         return 0;
595 }
596
597 #if 0 /// UNNEEDED by elogind
598 int inotify_add_watch_fd(int fd, int what, uint32_t mask) {
599         char path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
600         int r;
601
602         /* This is like inotify_add_watch(), except that the file to watch is not referenced by a path, but by an fd */
603         xsprintf(path, "/proc/self/fd/%i", what);
604
605         r = inotify_add_watch(fd, path, mask);
606         if (r < 0)
607                 return -errno;
608
609         return r;
610 }
611 #endif // 0
612
613 static bool safe_transition(const struct stat *a, const struct stat *b) {
614         /* Returns true if the transition from a to b is safe, i.e. that we never transition from unprivileged to
615          * privileged files or directories. Why bother? So that unprivileged code can't symlink to privileged files
616          * making us believe we read something safe even though it isn't safe in the specific context we open it in. */
617
618         if (a->st_uid == 0) /* Transitioning from privileged to unprivileged is always fine */
619                 return true;
620
621         return a->st_uid == b->st_uid; /* Otherwise we need to stay within the same UID */
622 }
623
624 int chase_symlinks(const char *path, const char *original_root, unsigned flags, char **ret) {
625         _cleanup_free_ char *buffer = NULL, *done = NULL, *root = NULL;
626         _cleanup_close_ int fd = -1;
627         unsigned max_follow = CHASE_SYMLINKS_MAX; /* how many symlinks to follow before giving up and returning ELOOP */
628         struct stat previous_stat;
629         bool exists = true;
630         char *todo;
631         int r;
632
633         assert(path);
634
635         /* Either the file may be missing, or we return an fd to the final object, but both make no sense */
636         if (FLAGS_SET(flags, CHASE_NONEXISTENT | CHASE_OPEN))
637                 return -EINVAL;
638
639         if (FLAGS_SET(flags, CHASE_STEP | CHASE_OPEN))
640                 return -EINVAL;
641
642         if (isempty(path))
643                 return -EINVAL;
644
645         /* This is a lot like canonicalize_file_name(), but takes an additional "root" parameter, that allows following
646          * symlinks relative to a root directory, instead of the root of the host.
647          *
648          * Note that "root" primarily matters if we encounter an absolute symlink. It is also used when following
649          * relative symlinks to ensure they cannot be used to "escape" the root directory. The path parameter passed is
650          * assumed to be already prefixed by it, except if the CHASE_PREFIX_ROOT flag is set, in which case it is first
651          * prefixed accordingly.
652          *
653          * Algorithmically this operates on two path buffers: "done" are the components of the path we already
654          * processed and resolved symlinks, "." and ".." of. "todo" are the components of the path we still need to
655          * process. On each iteration, we move one component from "todo" to "done", processing it's special meaning
656          * each time. The "todo" path always starts with at least one slash, the "done" path always ends in no
657          * slash. We always keep an O_PATH fd to the component we are currently processing, thus keeping lookup races
658          * at a minimum.
659          *
660          * Suggested usage: whenever you want to canonicalize a path, use this function. Pass the absolute path you got
661          * as-is: fully qualified and relative to your host's root. Optionally, specify the root parameter to tell this
662          * function what to do when encountering a symlink with an absolute path as directory: prefix it by the
663          * specified path.
664          *
665          * There are three ways to invoke this function:
666          *
667          * 1. Without CHASE_STEP or CHASE_OPEN: in this case the path is resolved and the normalized path is returned
668          *    in `ret`. The return value is < 0 on error. If CHASE_NONEXISTENT is also set 0 is returned if the file
669          *    doesn't exist, > 0 otherwise. If CHASE_NONEXISTENT is not set >= 0 is returned if the destination was
670          *    found, -ENOENT if it doesn't.
671          *
672          * 2. With CHASE_OPEN: in this case the destination is opened after chasing it as O_PATH and this file
673          *    descriptor is returned as return value. This is useful to open files relative to some root
674          *    directory. Note that the returned O_PATH file descriptors must be converted into a regular one (using
675          *    fd_reopen() or such) before it can be used for reading/writing. CHASE_OPEN may not be combined with
676          *    CHASE_NONEXISTENT.
677          *
678          * 3. With CHASE_STEP: in this case only a single step of the normalization is executed, i.e. only the first
679          *    symlink or ".." component of the path is resolved, and the resulting path is returned. This is useful if
680          *    a caller wants to trace the a path through the file system verbosely. Returns < 0 on error, > 0 if the
681          *    path is fully normalized, and == 0 for each normalization step. This may be combined with
682          *    CHASE_NONEXISTENT, in which case 1 is returned when a component is not found.
683          *
684          * */
685
686         /* A root directory of "/" or "" is identical to none */
687         if (empty_or_root(original_root))
688                 original_root = NULL;
689
690         if (!original_root && !ret && (flags & (CHASE_NONEXISTENT|CHASE_NO_AUTOFS|CHASE_SAFE|CHASE_OPEN|CHASE_STEP)) == CHASE_OPEN) {
691                 /* Shortcut the CHASE_OPEN case if the caller isn't interested in the actual path and has no root set
692                  * and doesn't care about any of the other special features we provide either. */
693                 r = open(path, O_PATH|O_CLOEXEC);
694                 if (r < 0)
695                         return -errno;
696
697                 return r;
698         }
699
700         if (original_root) {
701                 r = path_make_absolute_cwd(original_root, &root);
702                 if (r < 0)
703                         return r;
704
705                 if (flags & CHASE_PREFIX_ROOT) {
706
707                         /* We don't support relative paths in combination with a root directory */
708                         if (!path_is_absolute(path))
709                                 return -EINVAL;
710
711                         path = prefix_roota(root, path);
712                 }
713         }
714
715         r = path_make_absolute_cwd(path, &buffer);
716         if (r < 0)
717                 return r;
718
719         fd = open("/", O_CLOEXEC|O_NOFOLLOW|O_PATH);
720         if (fd < 0)
721                 return -errno;
722
723         if (flags & CHASE_SAFE) {
724                 if (fstat(fd, &previous_stat) < 0)
725                         return -errno;
726         }
727
728         todo = buffer;
729         for (;;) {
730                 _cleanup_free_ char *first = NULL;
731                 _cleanup_close_ int child = -1;
732                 struct stat st;
733                 size_t n, m;
734
735                 /* Determine length of first component in the path */
736                 n = strspn(todo, "/");                  /* The slashes */
737                 m = n + strcspn(todo + n, "/");         /* The entire length of the component */
738
739                 /* Extract the first component. */
740                 first = strndup(todo, m);
741                 if (!first)
742                         return -ENOMEM;
743
744                 todo += m;
745
746                 /* Empty? Then we reached the end. */
747                 if (isempty(first))
748                         break;
749
750                 /* Just a single slash? Then we reached the end. */
751                 if (path_equal(first, "/")) {
752                         /* Preserve the trailing slash */
753
754                         if (flags & CHASE_TRAIL_SLASH)
755                                 if (!strextend(&done, "/", NULL))
756                                         return -ENOMEM;
757
758                         break;
759                 }
760
761                 /* Just a dot? Then let's eat this up. */
762                 if (path_equal(first, "/."))
763                         continue;
764
765                 /* Two dots? Then chop off the last bit of what we already found out. */
766                 if (path_equal(first, "/..")) {
767                         _cleanup_free_ char *parent = NULL;
768                         _cleanup_close_ int fd_parent = -1;
769
770                         /* If we already are at the top, then going up will not change anything. This is in-line with
771                          * how the kernel handles this. */
772                         if (empty_or_root(done))
773                                 continue;
774
775                         parent = dirname_malloc(done);
776                         if (!parent)
777                                 return -ENOMEM;
778
779                         /* Don't allow this to leave the root dir.  */
780                         if (root &&
781                             path_startswith(done, root) &&
782                             !path_startswith(parent, root))
783                                 continue;
784
785                         free_and_replace(done, parent);
786
787                         if (flags & CHASE_STEP)
788                                 goto chased_one;
789
790                         fd_parent = openat(fd, "..", O_CLOEXEC|O_NOFOLLOW|O_PATH);
791                         if (fd_parent < 0)
792                                 return -errno;
793
794                         if (flags & CHASE_SAFE) {
795                                 if (fstat(fd_parent, &st) < 0)
796                                         return -errno;
797
798                                 if (!safe_transition(&previous_stat, &st))
799                                         return -EPERM;
800
801                                 previous_stat = st;
802                         }
803
804                         safe_close(fd);
805                         fd = TAKE_FD(fd_parent);
806
807                         continue;
808                 }
809
810                 /* Otherwise let's see what this is. */
811                 child = openat(fd, first + n, O_CLOEXEC|O_NOFOLLOW|O_PATH);
812                 if (child < 0) {
813
814                         if (errno == ENOENT &&
815                             (flags & CHASE_NONEXISTENT) &&
816                             (isempty(todo) || path_is_normalized(todo))) {
817
818                                 /* If CHASE_NONEXISTENT is set, and the path does not exist, then that's OK, return
819                                  * what we got so far. But don't allow this if the remaining path contains "../ or "./"
820                                  * or something else weird. */
821
822                                 /* If done is "/", as first also contains slash at the head, then remove this redundant slash. */
823                                 if (streq_ptr(done, "/"))
824                                         *done = '\0';
825
826                                 if (!strextend(&done, first, todo, NULL))
827                                         return -ENOMEM;
828
829                                 exists = false;
830                                 break;
831                         }
832
833                         return -errno;
834                 }
835
836                 if (fstat(child, &st) < 0)
837                         return -errno;
838                 if ((flags & CHASE_SAFE) &&
839                     !safe_transition(&previous_stat, &st))
840                         return -EPERM;
841
842                 previous_stat = st;
843
844                 if ((flags & CHASE_NO_AUTOFS) &&
845                     fd_is_fs_type(child, AUTOFS_SUPER_MAGIC) > 0)
846                         return -EREMOTE;
847
848                 if (S_ISLNK(st.st_mode)) {
849                         char *joined;
850
851                         _cleanup_free_ char *destination = NULL;
852
853                         /* This is a symlink, in this case read the destination. But let's make sure we don't follow
854                          * symlinks without bounds. */
855                         if (--max_follow <= 0)
856                                 return -ELOOP;
857
858                         r = readlinkat_malloc(fd, first + n, &destination);
859                         if (r < 0)
860                                 return r;
861                         if (isempty(destination))
862                                 return -EINVAL;
863
864                         if (path_is_absolute(destination)) {
865
866                                 /* An absolute destination. Start the loop from the beginning, but use the root
867                                  * directory as base. */
868
869                                 safe_close(fd);
870                                 fd = open(root ?: "/", O_CLOEXEC|O_NOFOLLOW|O_PATH);
871                                 if (fd < 0)
872                                         return -errno;
873
874                                 if (flags & CHASE_SAFE) {
875                                         if (fstat(fd, &st) < 0)
876                                                 return -errno;
877
878                                         if (!safe_transition(&previous_stat, &st))
879                                                 return -EPERM;
880
881                                         previous_stat = st;
882                                 }
883
884                                 free(done);
885
886                                 /* Note that we do not revalidate the root, we take it as is. */
887                                 if (isempty(root))
888                                         done = NULL;
889                                 else {
890                                         done = strdup(root);
891                                         if (!done)
892                                                 return -ENOMEM;
893                                 }
894
895                                 /* Prefix what's left to do with what we just read, and start the loop again, but
896                                  * remain in the current directory. */
897                                 joined = strjoin(destination, todo);
898                         } else
899                                 joined = strjoin("/", destination, todo);
900                         if (!joined)
901                                 return -ENOMEM;
902
903                         free(buffer);
904                         todo = buffer = joined;
905
906                         if (flags & CHASE_STEP)
907                                 goto chased_one;
908
909                         continue;
910                 }
911
912                 /* If this is not a symlink, then let's just add the name we read to what we already verified. */
913                 if (!done)
914                         done = TAKE_PTR(first);
915                 else {
916                         /* If done is "/", as first also contains slash at the head, then remove this redundant slash. */
917                         if (streq(done, "/"))
918                                 *done = '\0';
919
920                         if (!strextend(&done, first, NULL))
921                                 return -ENOMEM;
922                 }
923
924                 /* And iterate again, but go one directory further down. */
925                 safe_close(fd);
926                 fd = TAKE_FD(child);
927         }
928
929         if (!done) {
930                 /* Special case, turn the empty string into "/", to indicate the root directory. */
931                 done = strdup("/");
932                 if (!done)
933                         return -ENOMEM;
934         }
935
936         if (ret)
937                 *ret = TAKE_PTR(done);
938
939         if (flags & CHASE_OPEN) {
940                 /* Return the O_PATH fd we currently are looking to the caller. It can translate it to a proper fd by
941                  * opening /proc/self/fd/xyz. */
942
943                 assert(fd >= 0);
944                 return TAKE_FD(fd);
945         }
946
947         if (flags & CHASE_STEP)
948                 return 1;
949
950         return exists;
951
952 chased_one:
953         if (ret) {
954                 char *c;
955
956                 c = strjoin(strempty(done), todo);
957                 if (!c)
958                         return -ENOMEM;
959
960                 *ret = c;
961         }
962
963         return 0;
964 }
965
966 int chase_symlinks_and_open(
967                 const char *path,
968                 const char *root,
969                 unsigned chase_flags,
970                 int open_flags,
971                 char **ret_path) {
972
973         _cleanup_close_ int path_fd = -1;
974         _cleanup_free_ char *p = NULL;
975         int r;
976
977         if (chase_flags & CHASE_NONEXISTENT)
978                 return -EINVAL;
979
980         if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0) {
981                 /* Shortcut this call if none of the special features of this call are requested */
982                 r = open(path, open_flags);
983                 if (r < 0)
984                         return -errno;
985
986                 return r;
987         }
988
989         path_fd = chase_symlinks(path, root, chase_flags|CHASE_OPEN, ret_path ? &p : NULL);
990         if (path_fd < 0)
991                 return path_fd;
992
993         r = fd_reopen(path_fd, open_flags);
994         if (r < 0)
995                 return r;
996
997         if (ret_path)
998                 *ret_path = TAKE_PTR(p);
999
1000         return r;
1001 }
1002
1003 int chase_symlinks_and_opendir(
1004                 const char *path,
1005                 const char *root,
1006                 unsigned chase_flags,
1007                 char **ret_path,
1008                 DIR **ret_dir) {
1009
1010         char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1011         _cleanup_close_ int path_fd = -1;
1012         _cleanup_free_ char *p = NULL;
1013         DIR *d;
1014
1015         if (!ret_dir)
1016                 return -EINVAL;
1017         if (chase_flags & CHASE_NONEXISTENT)
1018                 return -EINVAL;
1019
1020         if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0) {
1021                 /* Shortcut this call if none of the special features of this call are requested */
1022                 d = opendir(path);
1023                 if (!d)
1024                         return -errno;
1025
1026                 *ret_dir = d;
1027                 return 0;
1028         }
1029
1030         path_fd = chase_symlinks(path, root, chase_flags|CHASE_OPEN, ret_path ? &p : NULL);
1031         if (path_fd < 0)
1032                 return path_fd;
1033
1034         xsprintf(procfs_path, "/proc/self/fd/%i", path_fd);
1035         d = opendir(procfs_path);
1036         if (!d)
1037                 return -errno;
1038
1039         if (ret_path)
1040                 *ret_path = TAKE_PTR(p);
1041
1042         *ret_dir = d;
1043         return 0;
1044 }
1045
1046 int chase_symlinks_and_stat(
1047                 const char *path,
1048                 const char *root,
1049                 unsigned chase_flags,
1050                 char **ret_path,
1051                 struct stat *ret_stat) {
1052
1053         _cleanup_close_ int path_fd = -1;
1054         _cleanup_free_ char *p = NULL;
1055
1056         assert(path);
1057         assert(ret_stat);
1058
1059         if (chase_flags & CHASE_NONEXISTENT)
1060                 return -EINVAL;
1061
1062         if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0) {
1063                 /* Shortcut this call if none of the special features of this call are requested */
1064                 if (stat(path, ret_stat) < 0)
1065                         return -errno;
1066
1067                 return 1;
1068         }
1069
1070         path_fd = chase_symlinks(path, root, chase_flags|CHASE_OPEN, ret_path ? &p : NULL);
1071         if (path_fd < 0)
1072                 return path_fd;
1073
1074         if (fstat(path_fd, ret_stat) < 0)
1075                 return -errno;
1076
1077         if (ret_path)
1078                 *ret_path = TAKE_PTR(p);
1079
1080         if (chase_flags & CHASE_OPEN)
1081                 return TAKE_FD(path_fd);
1082
1083         return 1;
1084 }
1085
1086 int access_fd(int fd, int mode) {
1087         char p[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
1088         int r;
1089
1090         /* Like access() but operates on an already open fd */
1091
1092         xsprintf(p, "/proc/self/fd/%i", fd);
1093         r = access(p, mode);
1094         if (r < 0)
1095                 return -errno;
1096
1097         return r;
1098 }
1099
1100 void unlink_tempfilep(char (*p)[]) {
1101         /* If the file is created with mkstemp(), it will (almost always)
1102          * change the suffix. Treat this as a sign that the file was
1103          * successfully created. We ignore both the rare case where the
1104          * original suffix is used and unlink failures. */
1105         if (!endswith(*p, ".XXXXXX"))
1106                 (void) unlink_noerrno(*p);
1107 }
1108
1109 int unlinkat_deallocate(int fd, const char *name, int flags) {
1110         _cleanup_close_ int truncate_fd = -1;
1111         struct stat st;
1112         off_t l, bs;
1113
1114         /* Operates like unlinkat() but also deallocates the file contents if it is a regular file and there's no other
1115          * link to it. This is useful to ensure that other processes that might have the file open for reading won't be
1116          * able to keep the data pinned on disk forever. This call is particular useful whenever we execute clean-up
1117          * jobs ("vacuuming"), where we want to make sure the data is really gone and the disk space released and
1118          * returned to the free pool.
1119          *
1120          * Deallocation is preferably done by FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE (👊) if supported, which means
1121          * the file won't change size. That's a good thing since we shouldn't needlessly trigger SIGBUS in other
1122          * programs that have mmap()ed the file. (The assumption here is that changing file contents to all zeroes
1123          * underneath those programs is the better choice than simply triggering SIGBUS in them which truncation does.)
1124          * However if hole punching is not implemented in the kernel or file system we'll fall back to normal file
1125          * truncation (đŸ”Ē), as our goal of deallocating the data space trumps our goal of being nice to readers (💐).
1126          *
1127          * Note that we attempt deallocation, but failure to succeed with that is not considered fatal, as long as the
1128          * primary job â€“ to delete the file â€“ is accomplished. */
1129
1130         if ((flags & AT_REMOVEDIR) == 0) {
1131                 truncate_fd = openat(fd, name, O_WRONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW|O_NONBLOCK);
1132                 if (truncate_fd < 0) {
1133
1134                         /* If this failed because the file doesn't exist propagate the error right-away. Also,
1135                          * AT_REMOVEDIR wasn't set, and we tried to open the file for writing, which means EISDIR is
1136                          * returned when this is a directory but we are not supposed to delete those, hence propagate
1137                          * the error right-away too. */
1138                         if (IN_SET(errno, ENOENT, EISDIR))
1139                                 return -errno;
1140
1141                         if (errno != ELOOP) /* don't complain if this is a symlink */
1142                                 log_debug_errno(errno, "Failed to open file '%s' for deallocation, ignoring: %m", name);
1143                 }
1144         }
1145
1146         if (unlinkat(fd, name, flags) < 0)
1147                 return -errno;
1148
1149         if (truncate_fd < 0) /* Don't have a file handle, can't do more â˜šī¸ */
1150                 return 0;
1151
1152         if (fstat(truncate_fd, &st) < 0) {
1153                 log_debug_errno(errno, "Failed to stat file '%s' for deallocation, ignoring.", name);
1154                 return 0;
1155         }
1156
1157         if (!S_ISREG(st.st_mode) || st.st_blocks == 0 || st.st_nlink > 0)
1158                 return 0;
1159
1160         /* If this is a regular file, it actually took up space on disk and there are no other links it's time to
1161          * punch-hole/truncate this to release the disk space. */
1162
1163         bs = MAX(st.st_blksize, 512);
1164         l = DIV_ROUND_UP(st.st_size, bs) * bs; /* Round up to next block size */
1165
1166         if (fallocate(truncate_fd, FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE, 0, l) >= 0)
1167                 return 0; /* Successfully punched a hole! đŸ˜Š */
1168
1169         /* Fall back to truncation */
1170         if (ftruncate(truncate_fd, 0) < 0) {
1171                 log_debug_errno(errno, "Failed to truncate file to 0, ignoring: %m");
1172                 return 0;
1173         }
1174
1175         return 0;
1176 }
1177
1178 int fsync_directory_of_file(int fd) {
1179         _cleanup_free_ char *path = NULL, *dn = NULL;
1180         _cleanup_close_ int dfd = -1;
1181         int r;
1182
1183         r = fd_verify_regular(fd);
1184         if (r < 0)
1185                 return r;
1186
1187         r = fd_get_path(fd, &path);
1188         if (r < 0) {
1189                 log_debug_errno(r, "Failed to query /proc/self/fd/%d%s: %m",
1190                                 fd,
1191                                 r == -EOPNOTSUPP ? ", ignoring" : "");
1192
1193                 if (r == -EOPNOTSUPP)
1194                         /* If /proc is not available, we're most likely running in some
1195                          * chroot environment, and syncing the directory is not very
1196                          * important in that case. Let's just silently do nothing. */
1197                         return 0;
1198
1199                 return r;
1200         }
1201
1202         if (!path_is_absolute(path))
1203                 return -EINVAL;
1204
1205         dn = dirname_malloc(path);
1206         if (!dn)
1207                 return -ENOMEM;
1208
1209         dfd = open(dn, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
1210         if (dfd < 0)
1211                 return -errno;
1212
1213         if (fsync(dfd) < 0)
1214                 return -errno;
1215
1216         return 0;
1217 }