]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/fs-util.c
network: drop many unnecessary link_dirty() calls
[thirdparty/systemd.git] / src / basic / fs-util.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
f4f15635 2
11c3a366
TA
3#include <errno.h>
4#include <stddef.h>
11c3a366 5#include <stdlib.h>
1c73b069 6#include <linux/falloc.h>
655f2da0 7#include <linux/magic.h>
11c3a366
TA
8#include <unistd.h>
9
b5efdb8a 10#include "alloc-util.h"
ed9c0851 11#include "blockdev-util.h"
f4f15635
LP
12#include "dirent-util.h"
13#include "fd-util.h"
ed9c0851 14#include "fileio.h"
f4f15635 15#include "fs-util.h"
fd74c6f3 16#include "locale-util.h"
11c3a366
TA
17#include "log.h"
18#include "macro.h"
0499585f 19#include "missing_fcntl.h"
f5947a5e
YW
20#include "missing_fs.h"
21#include "missing_syscall.h"
93cc7779
TA
22#include "mkdir.h"
23#include "parse-util.h"
24#include "path-util.h"
dccca82b 25#include "process-util.h"
053e0626 26#include "random-util.h"
34a8f081 27#include "stat-util.h"
430fbf8e 28#include "stdio-util.h"
f4f15635
LP
29#include "string-util.h"
30#include "strv.h"
93cc7779 31#include "time-util.h"
e4de7287 32#include "tmpfile-util.h"
ee104e11 33#include "user-util.h"
f4f15635
LP
34#include "util.h"
35
36int unlink_noerrno(const char *path) {
37 PROTECT_ERRNO;
38 int r;
39
40 r = unlink(path);
41 if (r < 0)
42 return -errno;
43
44 return 0;
45}
46
47int rmdir_parents(const char *path, const char *stop) {
48 size_t l;
49 int r = 0;
50
51 assert(path);
52 assert(stop);
53
54 l = strlen(path);
55
56 /* Skip trailing slashes */
57 while (l > 0 && path[l-1] == '/')
58 l--;
59
60 while (l > 0) {
61 char *t;
62
63 /* Skip last component */
64 while (l > 0 && path[l-1] != '/')
65 l--;
66
67 /* Skip trailing slashes */
68 while (l > 0 && path[l-1] == '/')
69 l--;
70
71 if (l <= 0)
72 break;
73
74 t = strndup(path, l);
75 if (!t)
76 return -ENOMEM;
77
78 if (path_startswith(stop, t)) {
79 free(t);
80 return 0;
81 }
82
83 r = rmdir(t);
84 free(t);
85
86 if (r < 0)
87 if (errno != ENOENT)
88 return -errno;
89 }
90
91 return 0;
92}
93
f4f15635 94int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
2f15b625 95 int r;
f4f15635 96
2f15b625
LP
97 /* Try the ideal approach first */
98 if (renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE) >= 0)
f4f15635
LP
99 return 0;
100
2f15b625
LP
101 /* renameat2() exists since Linux 3.15, btrfs and FAT added support for it later. If it is not implemented,
102 * fall back to a different method. */
103 if (!IN_SET(errno, EINVAL, ENOSYS, ENOTTY))
f4f15635
LP
104 return -errno;
105
2f15b625
LP
106 /* Let's try to use linkat()+unlinkat() as fallback. This doesn't work on directories and on some file systems
107 * that do not support hard links (such as FAT, most prominently), but for files it's pretty close to what we
108 * want — though not atomic (i.e. for a short period both the new and the old filename will exist). */
109 if (linkat(olddirfd, oldpath, newdirfd, newpath, 0) >= 0) {
110
111 if (unlinkat(olddirfd, oldpath, 0) < 0) {
112 r = -errno; /* Backup errno before the following unlinkat() alters it */
113 (void) unlinkat(newdirfd, newpath, 0);
114 return r;
115 }
116
117 return 0;
f4f15635
LP
118 }
119
2f15b625 120 if (!IN_SET(errno, EINVAL, ENOSYS, ENOTTY, EPERM)) /* FAT returns EPERM on link()… */
f4f15635
LP
121 return -errno;
122
2aed63f4 123 /* OK, neither RENAME_NOREPLACE nor linkat()+unlinkat() worked. Let's then fall back to the racy TOCTOU
2f15b625
LP
124 * vulnerable accessat(F_OK) check followed by classic, replacing renameat(), we have nothing better. */
125
126 if (faccessat(newdirfd, newpath, F_OK, AT_SYMLINK_NOFOLLOW) >= 0)
127 return -EEXIST;
128 if (errno != ENOENT)
129 return -errno;
130
131 if (renameat(olddirfd, oldpath, newdirfd, newpath) < 0)
f4f15635 132 return -errno;
f4f15635
LP
133
134 return 0;
135}
136
137int readlinkat_malloc(int fd, const char *p, char **ret) {
8e060ec2 138 size_t l = FILENAME_MAX+1;
f4f15635
LP
139 int r;
140
141 assert(p);
142 assert(ret);
143
144 for (;;) {
145 char *c;
146 ssize_t n;
147
148 c = new(char, l);
149 if (!c)
150 return -ENOMEM;
151
152 n = readlinkat(fd, p, c, l-1);
153 if (n < 0) {
154 r = -errno;
155 free(c);
156 return r;
157 }
158
159 if ((size_t) n < l-1) {
160 c[n] = 0;
161 *ret = c;
162 return 0;
163 }
164
165 free(c);
166 l *= 2;
167 }
168}
169
170int readlink_malloc(const char *p, char **ret) {
171 return readlinkat_malloc(AT_FDCWD, p, ret);
172}
173
174int readlink_value(const char *p, char **ret) {
175 _cleanup_free_ char *link = NULL;
176 char *value;
177 int r;
178
179 r = readlink_malloc(p, &link);
180 if (r < 0)
181 return r;
182
183 value = basename(link);
184 if (!value)
185 return -ENOENT;
186
187 value = strdup(value);
188 if (!value)
189 return -ENOMEM;
190
191 *ret = value;
192
193 return 0;
194}
195
196int readlink_and_make_absolute(const char *p, char **r) {
197 _cleanup_free_ char *target = NULL;
198 char *k;
199 int j;
200
201 assert(p);
202 assert(r);
203
204 j = readlink_malloc(p, &target);
205 if (j < 0)
206 return j;
207
208 k = file_in_same_dir(p, target);
209 if (!k)
210 return -ENOMEM;
211
212 *r = k;
213 return 0;
214}
215
f4f15635 216int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
de321f52 217 _cleanup_close_ int fd = -1;
30ff18d8 218
f4f15635
LP
219 assert(path);
220
30ff18d8
LP
221 fd = open(path, O_PATH|O_CLOEXEC|O_NOFOLLOW); /* Let's acquire an O_PATH fd, as precaution to change
222 * mode/owner on the same file */
de321f52
LP
223 if (fd < 0)
224 return -errno;
225
2dbb7e94 226 return fchmod_and_chown(fd, mode, uid, gid);
b8da477e
YW
227}
228
229int fchmod_and_chown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2dbb7e94 230 bool do_chown, do_chmod;
30ff18d8 231 struct stat st;
dee00c19 232 int r;
30ff18d8 233
2dbb7e94
LP
234 /* Change ownership and access mode of the specified fd. Tries to do so safely, ensuring that at no
235 * point in time the access mode is above the old access mode under the old ownership or the new
236 * access mode under the new ownership. Note: this call tries hard to leave the access mode
237 * unaffected if the uid/gid is changed, i.e. it undoes implicit suid/sgid dropping the kernel does
238 * on chown().
239 *
71ec74d1 240 * This call is happy with O_PATH fds. */
b8da477e 241
71ec74d1 242 if (fstat(fd, &st) < 0)
2dbb7e94 243 return -errno;
de321f52 244
2dbb7e94
LP
245 do_chown =
246 (uid != UID_INVALID && st.st_uid != uid) ||
247 (gid != GID_INVALID && st.st_gid != gid);
de321f52 248
2dbb7e94
LP
249 do_chmod =
250 !S_ISLNK(st.st_mode) && /* chmod is not defined on symlinks */
251 ((mode != MODE_INVALID && ((st.st_mode ^ mode) & 07777) != 0) ||
252 do_chown); /* If we change ownership, make sure we reset the mode afterwards, since chown()
253 * modifies the access mode too */
30ff18d8 254
2dbb7e94
LP
255 if (mode == MODE_INVALID)
256 mode = st.st_mode; /* If we only shall do a chown(), save original mode, since chown() might break it. */
257 else if ((mode & S_IFMT) != 0 && ((mode ^ st.st_mode) & S_IFMT) != 0)
258 return -EINVAL; /* insist on the right file type if it was specified */
de321f52 259
2dbb7e94
LP
260 if (do_chown && do_chmod) {
261 mode_t minimal = st.st_mode & mode; /* the subset of the old and the new mask */
30ff18d8 262
dee00c19
LP
263 if (((minimal ^ st.st_mode) & 07777) != 0) {
264 r = fchmod_opath(fd, minimal & 07777);
265 if (r < 0)
266 return r;
267 }
de321f52 268 }
b8da477e 269
2dbb7e94 270 if (do_chown)
71ec74d1 271 if (fchownat(fd, "", uid, gid, AT_EMPTY_PATH) < 0)
2dbb7e94 272 return -errno;
30ff18d8 273
dee00c19
LP
274 if (do_chmod) {
275 r = fchmod_opath(fd, mode & 07777);
276 if (r < 0)
277 return r;
278 }
30ff18d8 279
2dbb7e94 280 return do_chown || do_chmod;
f4f15635
LP
281}
282
f4f15635
LP
283int fchmod_umask(int fd, mode_t m) {
284 mode_t u;
285 int r;
286
287 u = umask(0777);
288 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
289 umask(u);
290
291 return r;
292}
293
4dfaa528 294int fchmod_opath(int fd, mode_t m) {
22dd8d35 295 char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
4dfaa528
FB
296
297 /* This function operates also on fd that might have been opened with
298 * O_PATH. Indeed fchmodat() doesn't have the AT_EMPTY_PATH flag like
299 * fchownat() does. */
300
301 xsprintf(procfs_path, "/proc/self/fd/%i", fd);
f8606626
LP
302 if (chmod(procfs_path, m) < 0) {
303 if (errno != ENOENT)
304 return -errno;
305
306 if (proc_mounted() == 0)
307 return -ENOSYS; /* if we have no /proc/, the concept is not implementable */
308
309 return -ENOENT;
310 }
4dfaa528
FB
311
312 return 0;
313}
314
f25bff5e
LP
315int futimens_opath(int fd, const struct timespec ts[2]) {
316 char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
317
318 /* Similar to fchmod_path() but for futimens() */
319
320 xsprintf(procfs_path, "/proc/self/fd/%i", fd);
321 if (utimensat(AT_FDCWD, procfs_path, ts, 0) < 0) {
322 if (errno != ENOENT)
323 return -errno;
324
325 if (proc_mounted() == 0)
326 return -ENOSYS; /* if we have no /proc/, the concept is not implementable */
327
328 return -ENOENT;
329 }
330
331 return 0;
332}
333
22ed4a6d
LP
334int stat_warn_permissions(const char *path, const struct stat *st) {
335 assert(path);
336 assert(st);
f4f15635 337
b6cceaae 338 /* Don't complain if we are reading something that is not a file, for example /dev/null */
22ed4a6d 339 if (!S_ISREG(st->st_mode))
b6cceaae
LP
340 return 0;
341
22ed4a6d 342 if (st->st_mode & 0111)
f4f15635
LP
343 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
344
22ed4a6d 345 if (st->st_mode & 0002)
f4f15635
LP
346 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
347
22ed4a6d 348 if (getpid_cached() == 1 && (st->st_mode & 0044) != 0044)
f4f15635
LP
349 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);
350
351 return 0;
352}
353
22ed4a6d
LP
354int fd_warn_permissions(const char *path, int fd) {
355 struct stat st;
356
357 assert(path);
358 assert(fd >= 0);
359
360 if (fstat(fd, &st) < 0)
361 return -errno;
362
363 return stat_warn_permissions(path, &st);
364}
365
f4f15635 366int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
9e3fa6e8
LP
367 char fdpath[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
368 _cleanup_close_ int fd = -1;
369 int r, ret = 0;
f4f15635
LP
370
371 assert(path);
372
9e3fa6e8
LP
373 /* Note that touch_file() does not follow symlinks: if invoked on an existing symlink, then it is the symlink
374 * itself which is updated, not its target
375 *
376 * Returns the first error we encounter, but tries to apply as much as possible. */
f4f15635 377
9e3fa6e8
LP
378 if (parents)
379 (void) mkdir_parents(path, 0755);
380
381 /* Initially, we try to open the node with O_PATH, so that we get a reference to the node. This is useful in
382 * case the path refers to an existing device or socket node, as we can open it successfully in all cases, and
383 * won't trigger any driver magic or so. */
384 fd = open(path, O_PATH|O_CLOEXEC|O_NOFOLLOW);
385 if (fd < 0) {
386 if (errno != ENOENT)
f4f15635 387 return -errno;
f4f15635 388
9e3fa6e8
LP
389 /* if the node doesn't exist yet, we create it, but with O_EXCL, so that we only create a regular file
390 * here, and nothing else */
391 fd = open(path, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC, IN_SET(mode, 0, MODE_INVALID) ? 0644 : mode);
392 if (fd < 0)
f4f15635
LP
393 return -errno;
394 }
395
9e3fa6e8
LP
396 /* Let's make a path from the fd, and operate on that. With this logic, we can adjust the access mode,
397 * ownership and time of the file node in all cases, even if the fd refers to an O_PATH object — which is
398 * something fchown(), fchmod(), futimensat() don't allow. */
399 xsprintf(fdpath, "/proc/self/fd/%i", fd);
400
4b3b5bc7 401 ret = fchmod_and_chown(fd, mode, uid, gid);
9e3fa6e8 402
f4f15635
LP
403 if (stamp != USEC_INFINITY) {
404 struct timespec ts[2];
405
406 timespec_store(&ts[0], stamp);
407 ts[1] = ts[0];
9e3fa6e8 408 r = utimensat(AT_FDCWD, fdpath, ts, 0);
f4f15635 409 } else
9e3fa6e8
LP
410 r = utimensat(AT_FDCWD, fdpath, NULL, 0);
411 if (r < 0 && ret >= 0)
f4f15635
LP
412 return -errno;
413
9e3fa6e8 414 return ret;
f4f15635
LP
415}
416
417int touch(const char *path) {
ee735086 418 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
f4f15635
LP
419}
420
6c9c51e5
YW
421int symlink_idempotent(const char *from, const char *to, bool make_relative) {
422 _cleanup_free_ char *relpath = NULL;
f4f15635
LP
423 int r;
424
425 assert(from);
426 assert(to);
427
6c9c51e5
YW
428 if (make_relative) {
429 _cleanup_free_ char *parent = NULL;
430
431 parent = dirname_malloc(to);
432 if (!parent)
433 return -ENOMEM;
434
435 r = path_make_relative(parent, from, &relpath);
436 if (r < 0)
437 return r;
438
439 from = relpath;
440 }
441
f4f15635 442 if (symlink(from, to) < 0) {
77b79723
LP
443 _cleanup_free_ char *p = NULL;
444
f4f15635
LP
445 if (errno != EEXIST)
446 return -errno;
447
448 r = readlink_malloc(to, &p);
77b79723
LP
449 if (r == -EINVAL) /* Not a symlink? In that case return the original error we encountered: -EEXIST */
450 return -EEXIST;
451 if (r < 0) /* Any other error? In that case propagate it as is */
f4f15635
LP
452 return r;
453
77b79723
LP
454 if (!streq(p, from)) /* Not the symlink we want it to be? In that case, propagate the original -EEXIST */
455 return -EEXIST;
f4f15635
LP
456 }
457
458 return 0;
459}
460
461int symlink_atomic(const char *from, const char *to) {
462 _cleanup_free_ char *t = NULL;
463 int r;
464
465 assert(from);
466 assert(to);
467
468 r = tempfn_random(to, NULL, &t);
469 if (r < 0)
470 return r;
471
472 if (symlink(from, t) < 0)
473 return -errno;
474
475 if (rename(t, to) < 0) {
476 unlink_noerrno(t);
477 return -errno;
478 }
479
480 return 0;
481}
482
483int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
484 _cleanup_free_ char *t = NULL;
485 int r;
486
487 assert(path);
488
489 r = tempfn_random(path, NULL, &t);
490 if (r < 0)
491 return r;
492
493 if (mknod(t, mode, dev) < 0)
494 return -errno;
495
496 if (rename(t, path) < 0) {
497 unlink_noerrno(t);
498 return -errno;
499 }
500
501 return 0;
502}
503
504int mkfifo_atomic(const char *path, mode_t mode) {
505 _cleanup_free_ char *t = NULL;
506 int r;
507
508 assert(path);
509
510 r = tempfn_random(path, NULL, &t);
511 if (r < 0)
512 return r;
513
514 if (mkfifo(t, mode) < 0)
515 return -errno;
516
517 if (rename(t, path) < 0) {
4fe3828c
FB
518 unlink_noerrno(t);
519 return -errno;
520 }
521
522 return 0;
523}
524
525int mkfifoat_atomic(int dirfd, const char *path, mode_t mode) {
526 _cleanup_free_ char *t = NULL;
527 int r;
528
529 assert(path);
530
531 if (path_is_absolute(path))
532 return mkfifo_atomic(path, mode);
533
534 /* We're only interested in the (random) filename. */
535 r = tempfn_random_child("", NULL, &t);
536 if (r < 0)
537 return r;
538
539 if (mkfifoat(dirfd, t, mode) < 0)
540 return -errno;
541
542 if (renameat(dirfd, t, dirfd, path) < 0) {
f4f15635
LP
543 unlink_noerrno(t);
544 return -errno;
545 }
546
547 return 0;
548}
549
550int get_files_in_directory(const char *path, char ***list) {
551 _cleanup_closedir_ DIR *d = NULL;
8fb3f009 552 struct dirent *de;
f4f15635
LP
553 size_t bufsize = 0, n = 0;
554 _cleanup_strv_free_ char **l = NULL;
555
556 assert(path);
557
558 /* Returns all files in a directory in *list, and the number
559 * of files as return value. If list is NULL returns only the
560 * number. */
561
562 d = opendir(path);
563 if (!d)
564 return -errno;
565
8fb3f009 566 FOREACH_DIRENT_ALL(de, d, return -errno) {
f4f15635
LP
567 dirent_ensure_type(d, de);
568
569 if (!dirent_is_file(de))
570 continue;
571
572 if (list) {
573 /* one extra slot is needed for the terminating NULL */
574 if (!GREEDY_REALLOC(l, bufsize, n + 2))
575 return -ENOMEM;
576
577 l[n] = strdup(de->d_name);
578 if (!l[n])
579 return -ENOMEM;
580
581 l[++n] = NULL;
582 } else
583 n++;
584 }
585
ae2a15bc
LP
586 if (list)
587 *list = TAKE_PTR(l);
f4f15635
LP
588
589 return n;
590}
430fbf8e 591
992e8f22
LP
592static int getenv_tmp_dir(const char **ret_path) {
593 const char *n;
594 int r, ret = 0;
34a8f081 595
992e8f22 596 assert(ret_path);
34a8f081 597
992e8f22
LP
598 /* We use the same order of environment variables python uses in tempfile.gettempdir():
599 * https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir */
600 FOREACH_STRING(n, "TMPDIR", "TEMP", "TMP") {
601 const char *e;
602
603 e = secure_getenv(n);
604 if (!e)
605 continue;
606 if (!path_is_absolute(e)) {
607 r = -ENOTDIR;
608 goto next;
609 }
99be45a4 610 if (!path_is_normalized(e)) {
992e8f22
LP
611 r = -EPERM;
612 goto next;
613 }
614
615 r = is_dir(e, true);
616 if (r < 0)
617 goto next;
618 if (r == 0) {
619 r = -ENOTDIR;
620 goto next;
621 }
622
623 *ret_path = e;
624 return 1;
625
626 next:
627 /* Remember first error, to make this more debuggable */
628 if (ret >= 0)
629 ret = r;
34a8f081
OW
630 }
631
992e8f22
LP
632 if (ret < 0)
633 return ret;
34a8f081 634
992e8f22
LP
635 *ret_path = NULL;
636 return ret;
637}
34a8f081 638
992e8f22
LP
639static int tmp_dir_internal(const char *def, const char **ret) {
640 const char *e;
641 int r, k;
642
643 assert(def);
644 assert(ret);
645
646 r = getenv_tmp_dir(&e);
647 if (r > 0) {
648 *ret = e;
649 return 0;
650 }
651
652 k = is_dir(def, true);
653 if (k == 0)
654 k = -ENOTDIR;
655 if (k < 0)
656 return r < 0 ? r : k;
657
658 *ret = def;
34a8f081
OW
659 return 0;
660}
661
992e8f22
LP
662int var_tmp_dir(const char **ret) {
663
664 /* Returns the location for "larger" temporary files, that is backed by physical storage if available, and thus
665 * even might survive a boot: /var/tmp. If $TMPDIR (or related environment variables) are set, its value is
666 * returned preferably however. Note that both this function and tmp_dir() below are affected by $TMPDIR,
667 * making it a variable that overrides all temporary file storage locations. */
668
669 return tmp_dir_internal("/var/tmp", ret);
670}
671
672int tmp_dir(const char **ret) {
673
674 /* Similar to var_tmp_dir() above, but returns the location for "smaller" temporary files, which is usually
675 * backed by an in-memory file system: /tmp. */
676
677 return tmp_dir_internal("/tmp", ret);
678}
679
af229d7a
ZJS
680int unlink_or_warn(const char *filename) {
681 if (unlink(filename) < 0 && errno != ENOENT)
682 /* If the file doesn't exist and the fs simply was read-only (in which
683 * case unlink() returns EROFS even if the file doesn't exist), don't
684 * complain */
685 if (errno != EROFS || access(filename, F_OK) >= 0)
686 return log_error_errno(errno, "Failed to remove \"%s\": %m", filename);
687
688 return 0;
689}
690
430fbf8e 691int inotify_add_watch_fd(int fd, int what, uint32_t mask) {
fbd0b64f 692 char path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
f6f4f5fe 693 int wd;
430fbf8e
LP
694
695 /* This is like inotify_add_watch(), except that the file to watch is not referenced by a path, but by an fd */
696 xsprintf(path, "/proc/self/fd/%i", what);
697
f6f4f5fe
BP
698 wd = inotify_add_watch(fd, path, mask);
699 if (wd < 0)
430fbf8e
LP
700 return -errno;
701
f6f4f5fe 702 return wd;
430fbf8e 703}
d944dc95 704
27c3112d 705int inotify_add_watch_and_warn(int fd, const char *pathname, uint32_t mask) {
f6f4f5fe 706 int wd;
27c3112d 707
f6f4f5fe
BP
708 wd = inotify_add_watch(fd, pathname, mask);
709 if (wd < 0) {
27c3112d 710 if (errno == ENOSPC)
fe573a79 711 return log_error_errno(errno, "Failed to add a watch for %s: inotify watch limit reached", pathname);
27c3112d 712
fe573a79 713 return log_error_errno(errno, "Failed to add a watch for %s: %m", pathname);
27c3112d
FB
714 }
715
f6f4f5fe 716 return wd;
27c3112d
FB
717}
718
b85ee2ec 719static bool unsafe_transition(const struct stat *a, const struct stat *b) {
f14f1806
LP
720 /* Returns true if the transition from a to b is safe, i.e. that we never transition from unprivileged to
721 * privileged files or directories. Why bother? So that unprivileged code can't symlink to privileged files
722 * making us believe we read something safe even though it isn't safe in the specific context we open it in. */
723
724 if (a->st_uid == 0) /* Transitioning from privileged to unprivileged is always fine */
b85ee2ec 725 return false;
f14f1806 726
b85ee2ec 727 return a->st_uid != b->st_uid; /* Otherwise we need to stay within the same UID */
f14f1806
LP
728}
729
fd74c6f3
FB
730static int log_unsafe_transition(int a, int b, const char *path, unsigned flags) {
731 _cleanup_free_ char *n1 = NULL, *n2 = NULL;
732
733 if (!FLAGS_SET(flags, CHASE_WARN))
36c97dec 734 return -ENOLINK;
fd74c6f3
FB
735
736 (void) fd_get_path(a, &n1);
737 (void) fd_get_path(b, &n2);
738
36c97dec 739 return log_warning_errno(SYNTHETIC_ERRNO(ENOLINK),
fd74c6f3 740 "Detected unsafe path transition %s %s %s during canonicalization of %s.",
48d837cd 741 strna(n1), special_glyph(SPECIAL_GLYPH_ARROW), strna(n2), path);
fd74c6f3
FB
742}
743
145b8d0f
FB
744static int log_autofs_mount_point(int fd, const char *path, unsigned flags) {
745 _cleanup_free_ char *n1 = NULL;
746
747 if (!FLAGS_SET(flags, CHASE_WARN))
748 return -EREMOTE;
749
750 (void) fd_get_path(fd, &n1);
751
752 return log_warning_errno(SYNTHETIC_ERRNO(EREMOTE),
753 "Detected autofs mount point %s during canonicalization of %s.",
48d837cd 754 strna(n1), path);
f14f1806
LP
755}
756
a5648b80 757int chase_symlinks(const char *path, const char *original_root, unsigned flags, char **ret_path, int *ret_fd) {
d944dc95
LP
758 _cleanup_free_ char *buffer = NULL, *done = NULL, *root = NULL;
759 _cleanup_close_ int fd = -1;
f10f4215 760 unsigned max_follow = CHASE_SYMLINKS_MAX; /* how many symlinks to follow before giving up and returning ELOOP */
f14f1806 761 struct stat previous_stat;
a9fb0867 762 bool exists = true;
d944dc95
LP
763 char *todo;
764 int r;
765
766 assert(path);
767
1ed34d75 768 /* Either the file may be missing, or we return an fd to the final object, but both make no sense */
a5648b80 769 if ((flags & CHASE_NONEXISTENT) && ret_fd)
1ed34d75
LP
770 return -EINVAL;
771
a5648b80 772 if ((flags & CHASE_STEP) && ret_fd)
49eb3659
LP
773 return -EINVAL;
774
a49424af
LP
775 if (isempty(path))
776 return -EINVAL;
777
d944dc95
LP
778 /* This is a lot like canonicalize_file_name(), but takes an additional "root" parameter, that allows following
779 * symlinks relative to a root directory, instead of the root of the host.
780 *
fc4b68e5 781 * Note that "root" primarily matters if we encounter an absolute symlink. It is also used when following
c4f4fce7
LP
782 * relative symlinks to ensure they cannot be used to "escape" the root directory. The path parameter passed is
783 * assumed to be already prefixed by it, except if the CHASE_PREFIX_ROOT flag is set, in which case it is first
784 * prefixed accordingly.
d944dc95
LP
785 *
786 * Algorithmically this operates on two path buffers: "done" are the components of the path we already
787 * processed and resolved symlinks, "." and ".." of. "todo" are the components of the path we still need to
788 * process. On each iteration, we move one component from "todo" to "done", processing it's special meaning
789 * each time. The "todo" path always starts with at least one slash, the "done" path always ends in no
790 * slash. We always keep an O_PATH fd to the component we are currently processing, thus keeping lookup races
4293c32b 791 * to a minimum.
fc4b68e5
LP
792 *
793 * Suggested usage: whenever you want to canonicalize a path, use this function. Pass the absolute path you got
794 * as-is: fully qualified and relative to your host's root. Optionally, specify the root parameter to tell this
795 * function what to do when encountering a symlink with an absolute path as directory: prefix it by the
49eb3659
LP
796 * specified path.
797 *
a5648b80 798 * There are five ways to invoke this function:
49eb3659 799 *
a5648b80
ZJS
800 * 1. Without CHASE_STEP or ret_fd: in this case the path is resolved and the normalized path is
801 * returned in `ret_path`. The return value is < 0 on error. If CHASE_NONEXISTENT is also set, 0
802 * is returned if the file doesn't exist, > 0 otherwise. If CHASE_NONEXISTENT is not set, >= 0 is
803 * returned if the destination was found, -ENOENT if it wasn't.
49eb3659 804 *
a5648b80 805 * 2. With ret_fd: in this case the destination is opened after chasing it as O_PATH and this file
49eb3659
LP
806 * descriptor is returned as return value. This is useful to open files relative to some root
807 * directory. Note that the returned O_PATH file descriptors must be converted into a regular one (using
a5648b80 808 * fd_reopen() or such) before it can be used for reading/writing. ret_fd may not be combined with
49eb3659
LP
809 * CHASE_NONEXISTENT.
810 *
811 * 3. With CHASE_STEP: in this case only a single step of the normalization is executed, i.e. only the first
812 * symlink or ".." component of the path is resolved, and the resulting path is returned. This is useful if
d51c4fca 813 * a caller wants to trace the path through the file system verbosely. Returns < 0 on error, > 0 if the
49eb3659
LP
814 * path is fully normalized, and == 0 for each normalization step. This may be combined with
815 * CHASE_NONEXISTENT, in which case 1 is returned when a component is not found.
816 *
36c97dec
FB
817 * 4. With CHASE_SAFE: in this case the path must not contain unsafe transitions, i.e. transitions from
818 * unprivileged to privileged files or directories. In such cases the return value is -ENOLINK. If
4293c32b 819 * CHASE_WARN is also set, a warning describing the unsafe transition is emitted.
36c97dec 820 *
4293c32b
ZJS
821 * 5. With CHASE_NO_AUTOFS: in this case if an autofs mount point is encountered, path normalization
822 * is aborted and -EREMOTE is returned. If CHASE_WARN is also set, a warning showing the path of
823 * the mount point is emitted.
4293c32b 824 */
d944dc95 825
22bc57c5 826 /* A root directory of "/" or "" is identical to none */
57ea45e1 827 if (empty_or_root(original_root))
22bc57c5 828 original_root = NULL;
b1bfb848 829
a5648b80
ZJS
830 if (!original_root && !ret_path && !(flags & (CHASE_NONEXISTENT|CHASE_NO_AUTOFS|CHASE_SAFE|CHASE_STEP)) && ret_fd) {
831 /* Shortcut the ret_fd case if the caller isn't interested in the actual path and has no root set
244d2f07 832 * and doesn't care about any of the other special features we provide either. */
1f56e4ce 833 r = open(path, O_PATH|O_CLOEXEC|((flags & CHASE_NOFOLLOW) ? O_NOFOLLOW : 0));
244d2f07
LP
834 if (r < 0)
835 return -errno;
836
a5648b80
ZJS
837 *ret_fd = r;
838 return 0;
244d2f07
LP
839 }
840
c4f4fce7
LP
841 if (original_root) {
842 r = path_make_absolute_cwd(original_root, &root);
d944dc95
LP
843 if (r < 0)
844 return r;
c4f4fce7 845
47d7ab72
LP
846 /* Simplify the root directory, so that it has no duplicate slashes and nothing at the
847 * end. While we won't resolve the root path we still simplify it. Note that dropping the
848 * trailing slash should not change behaviour, since when opening it we specify O_DIRECTORY
849 * anyway. Moreover at the end of this function after processing everything we'll always turn
850 * the empty string back to "/". */
851 delete_trailing_chars(root, "/");
852 path_simplify(root, true);
853
382a5078 854 if (flags & CHASE_PREFIX_ROOT) {
382a5078
LP
855 /* We don't support relative paths in combination with a root directory */
856 if (!path_is_absolute(path))
857 return -EINVAL;
858
c4f4fce7 859 path = prefix_roota(root, path);
382a5078 860 }
d944dc95
LP
861 }
862
c4f4fce7
LP
863 r = path_make_absolute_cwd(path, &buffer);
864 if (r < 0)
865 return r;
866
c2595d3b 867 fd = open(root ?: "/", O_CLOEXEC|O_DIRECTORY|O_PATH);
d944dc95
LP
868 if (fd < 0)
869 return -errno;
870
f14f1806
LP
871 if (flags & CHASE_SAFE) {
872 if (fstat(fd, &previous_stat) < 0)
873 return -errno;
874 }
875
c2595d3b
LP
876 if (root) {
877 _cleanup_free_ char *absolute = NULL;
878 const char *e;
879
880 /* If we are operating on a root directory, let's take the root directory as it is. */
881
882 e = path_startswith(buffer, root);
883 if (!e)
884 return log_full_errno(flags & CHASE_WARN ? LOG_WARNING : LOG_DEBUG,
885 SYNTHETIC_ERRNO(ECHRNG),
886 "Specified path '%s' is outside of specified root directory '%s', refusing to resolve.",
887 path, root);
888
c2595d3b
LP
889 done = strdup(root);
890 if (!done)
891 return -ENOMEM;
c2595d3b
LP
892
893 /* Make sure "todo" starts with a slash */
894 absolute = strjoin("/", e);
895 if (!absolute)
896 return -ENOMEM;
897
898 free_and_replace(buffer, absolute);
899 }
900
d944dc95
LP
901 todo = buffer;
902 for (;;) {
903 _cleanup_free_ char *first = NULL;
904 _cleanup_close_ int child = -1;
905 struct stat st;
906 size_t n, m;
907
908 /* Determine length of first component in the path */
909 n = strspn(todo, "/"); /* The slashes */
47d7ab72
LP
910
911 if (n > 1) {
912 /* If we are looking at more than a single slash then skip all but one, so that when
913 * we are done with everything we have a normalized path with only single slashes
914 * separating the path components. */
915 todo += n - 1;
916 n = 1;
917 }
918
d944dc95
LP
919 m = n + strcspn(todo + n, "/"); /* The entire length of the component */
920
921 /* Extract the first component. */
922 first = strndup(todo, m);
923 if (!first)
924 return -ENOMEM;
925
926 todo += m;
927
b12d25a8
ZJS
928 /* Empty? Then we reached the end. */
929 if (isempty(first))
930 break;
931
d944dc95 932 /* Just a single slash? Then we reached the end. */
b12d25a8
ZJS
933 if (path_equal(first, "/")) {
934 /* Preserve the trailing slash */
62570f6f
LP
935
936 if (flags & CHASE_TRAIL_SLASH)
c2bc710b 937 if (!strextend(&done, "/"))
62570f6f 938 return -ENOMEM;
b12d25a8 939
d944dc95 940 break;
b12d25a8 941 }
d944dc95
LP
942
943 /* Just a dot? Then let's eat this up. */
944 if (path_equal(first, "/."))
945 continue;
946
947 /* Two dots? Then chop off the last bit of what we already found out. */
948 if (path_equal(first, "/..")) {
949 _cleanup_free_ char *parent = NULL;
2b6d2dda 950 _cleanup_close_ int fd_parent = -1;
d944dc95 951
a4eaf3cf
LP
952 /* If we already are at the top, then going up will not change anything. This is in-line with
953 * how the kernel handles this. */
57ea45e1 954 if (empty_or_root(done))
a4eaf3cf 955 continue;
d944dc95
LP
956
957 parent = dirname_malloc(done);
958 if (!parent)
959 return -ENOMEM;
960
a4eaf3cf 961 /* Don't allow this to leave the root dir. */
d944dc95
LP
962 if (root &&
963 path_startswith(done, root) &&
964 !path_startswith(parent, root))
a4eaf3cf 965 continue;
d944dc95 966
3b319885 967 free_and_replace(done, parent);
d944dc95 968
49eb3659
LP
969 if (flags & CHASE_STEP)
970 goto chased_one;
971
d944dc95
LP
972 fd_parent = openat(fd, "..", O_CLOEXEC|O_NOFOLLOW|O_PATH);
973 if (fd_parent < 0)
974 return -errno;
975
f14f1806
LP
976 if (flags & CHASE_SAFE) {
977 if (fstat(fd_parent, &st) < 0)
978 return -errno;
979
b85ee2ec 980 if (unsafe_transition(&previous_stat, &st))
fd74c6f3 981 return log_unsafe_transition(fd, fd_parent, path, flags);
f14f1806
LP
982
983 previous_stat = st;
984 }
985
d944dc95 986 safe_close(fd);
c10d6bdb 987 fd = TAKE_FD(fd_parent);
d944dc95
LP
988
989 continue;
990 }
991
992 /* Otherwise let's see what this is. */
993 child = openat(fd, first + n, O_CLOEXEC|O_NOFOLLOW|O_PATH);
a9fb0867
LP
994 if (child < 0) {
995
996 if (errno == ENOENT &&
cb638b5e 997 (flags & CHASE_NONEXISTENT) &&
99be45a4 998 (isempty(todo) || path_is_normalized(todo))) {
a9fb0867 999
cb638b5e 1000 /* If CHASE_NONEXISTENT is set, and the path does not exist, then that's OK, return
a9fb0867
LP
1001 * what we got so far. But don't allow this if the remaining path contains "../ or "./"
1002 * or something else weird. */
1003
a1904a46
YW
1004 /* If done is "/", as first also contains slash at the head, then remove this redundant slash. */
1005 if (streq_ptr(done, "/"))
1006 *done = '\0';
1007
c2bc710b 1008 if (!strextend(&done, first, todo))
a9fb0867
LP
1009 return -ENOMEM;
1010
1011 exists = false;
1012 break;
1013 }
1014
d944dc95 1015 return -errno;
a9fb0867 1016 }
d944dc95
LP
1017
1018 if (fstat(child, &st) < 0)
1019 return -errno;
f14f1806 1020 if ((flags & CHASE_SAFE) &&
b85ee2ec 1021 unsafe_transition(&previous_stat, &st))
fd74c6f3 1022 return log_unsafe_transition(fd, child, path, flags);
f14f1806
LP
1023
1024 previous_stat = st;
1025
655f2da0 1026 if ((flags & CHASE_NO_AUTOFS) &&
a66fee2e 1027 fd_is_fs_type(child, AUTOFS_SUPER_MAGIC) > 0)
145b8d0f 1028 return log_autofs_mount_point(child, path, flags);
d944dc95 1029
1f56e4ce 1030 if (S_ISLNK(st.st_mode) && !((flags & CHASE_NOFOLLOW) && isempty(todo))) {
877777d7 1031 char *joined;
d944dc95
LP
1032 _cleanup_free_ char *destination = NULL;
1033
1034 /* This is a symlink, in this case read the destination. But let's make sure we don't follow
1035 * symlinks without bounds. */
1036 if (--max_follow <= 0)
1037 return -ELOOP;
1038
1039 r = readlinkat_malloc(fd, first + n, &destination);
1040 if (r < 0)
1041 return r;
1042 if (isempty(destination))
1043 return -EINVAL;
1044
1045 if (path_is_absolute(destination)) {
1046
1047 /* An absolute destination. Start the loop from the beginning, but use the root
1048 * directory as base. */
1049
1050 safe_close(fd);
c2595d3b 1051 fd = open(root ?: "/", O_CLOEXEC|O_DIRECTORY|O_PATH);
d944dc95
LP
1052 if (fd < 0)
1053 return -errno;
1054
f14f1806
LP
1055 if (flags & CHASE_SAFE) {
1056 if (fstat(fd, &st) < 0)
1057 return -errno;
1058
b85ee2ec 1059 if (unsafe_transition(&previous_stat, &st))
fd74c6f3 1060 return log_unsafe_transition(child, fd, path, flags);
f14f1806
LP
1061
1062 previous_stat = st;
1063 }
1064
b539437a
YW
1065 free(done);
1066
d944dc95
LP
1067 /* Note that we do not revalidate the root, we take it as is. */
1068 if (isempty(root))
1069 done = NULL;
1070 else {
1071 done = strdup(root);
1072 if (!done)
1073 return -ENOMEM;
1074 }
1075
8c4a8ea2
LP
1076 /* Prefix what's left to do with what we just read, and start the loop again, but
1077 * remain in the current directory. */
2d9b74ba 1078 joined = path_join(destination, todo);
8c4a8ea2 1079 } else
2d9b74ba 1080 joined = path_join("/", destination, todo);
877777d7
CCW
1081 if (!joined)
1082 return -ENOMEM;
d944dc95 1083
877777d7
CCW
1084 free(buffer);
1085 todo = buffer = joined;
d944dc95 1086
49eb3659
LP
1087 if (flags & CHASE_STEP)
1088 goto chased_one;
1089
d944dc95
LP
1090 continue;
1091 }
1092
1093 /* If this is not a symlink, then let's just add the name we read to what we already verified. */
ae2a15bc
LP
1094 if (!done)
1095 done = TAKE_PTR(first);
1096 else {
a1904a46
YW
1097 /* If done is "/", as first also contains slash at the head, then remove this redundant slash. */
1098 if (streq(done, "/"))
1099 *done = '\0';
1100
c2bc710b 1101 if (!strextend(&done, first))
d944dc95
LP
1102 return -ENOMEM;
1103 }
1104
1105 /* And iterate again, but go one directory further down. */
1106 safe_close(fd);
c10d6bdb 1107 fd = TAKE_FD(child);
d944dc95
LP
1108 }
1109
1110 if (!done) {
1111 /* Special case, turn the empty string into "/", to indicate the root directory. */
1112 done = strdup("/");
1113 if (!done)
1114 return -ENOMEM;
1115 }
1116
a5648b80
ZJS
1117 if (ret_path)
1118 *ret_path = TAKE_PTR(done);
d944dc95 1119
a5648b80
ZJS
1120 if (ret_fd) {
1121 /* Return the O_PATH fd we currently are looking to the caller. It can translate it to a
1122 * proper fd by opening /proc/self/fd/xyz. */
1ed34d75
LP
1123
1124 assert(fd >= 0);
a5648b80 1125 *ret_fd = TAKE_FD(fd);
1ed34d75
LP
1126 }
1127
49eb3659
LP
1128 if (flags & CHASE_STEP)
1129 return 1;
1130
a9fb0867 1131 return exists;
49eb3659
LP
1132
1133chased_one:
a5648b80 1134 if (ret_path) {
49eb3659
LP
1135 char *c;
1136
027cc9c9
ZJS
1137 c = strjoin(strempty(done), todo);
1138 if (!c)
1139 return -ENOMEM;
49eb3659 1140
a5648b80 1141 *ret_path = c;
49eb3659
LP
1142 }
1143
1144 return 0;
d944dc95 1145}
57a4359e 1146
21c692e9
LP
1147int chase_symlinks_and_open(
1148 const char *path,
1149 const char *root,
1150 unsigned chase_flags,
1151 int open_flags,
1152 char **ret_path) {
1153
1154 _cleanup_close_ int path_fd = -1;
1155 _cleanup_free_ char *p = NULL;
1156 int r;
1157
1158 if (chase_flags & CHASE_NONEXISTENT)
1159 return -EINVAL;
1160
57ea45e1 1161 if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0) {
21c692e9
LP
1162 /* Shortcut this call if none of the special features of this call are requested */
1163 r = open(path, open_flags);
1164 if (r < 0)
1165 return -errno;
1166
1167 return r;
1168 }
1169
a5648b80
ZJS
1170 r = chase_symlinks(path, root, chase_flags, ret_path ? &p : NULL, &path_fd);
1171 if (r < 0)
1172 return r;
1173 assert(path_fd >= 0);
21c692e9
LP
1174
1175 r = fd_reopen(path_fd, open_flags);
1176 if (r < 0)
1177 return r;
1178
1179 if (ret_path)
1180 *ret_path = TAKE_PTR(p);
1181
1182 return r;
1183}
1184
1185int chase_symlinks_and_opendir(
1186 const char *path,
1187 const char *root,
1188 unsigned chase_flags,
1189 char **ret_path,
1190 DIR **ret_dir) {
1191
1192 char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1193 _cleanup_close_ int path_fd = -1;
1194 _cleanup_free_ char *p = NULL;
1195 DIR *d;
a5648b80 1196 int r;
21c692e9
LP
1197
1198 if (!ret_dir)
1199 return -EINVAL;
1200 if (chase_flags & CHASE_NONEXISTENT)
1201 return -EINVAL;
1202
57ea45e1 1203 if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0) {
21c692e9
LP
1204 /* Shortcut this call if none of the special features of this call are requested */
1205 d = opendir(path);
1206 if (!d)
1207 return -errno;
1208
1209 *ret_dir = d;
1210 return 0;
1211 }
1212
a5648b80
ZJS
1213 r = chase_symlinks(path, root, chase_flags, ret_path ? &p : NULL, &path_fd);
1214 if (r < 0)
1215 return r;
1216 assert(path_fd >= 0);
21c692e9
LP
1217
1218 xsprintf(procfs_path, "/proc/self/fd/%i", path_fd);
1219 d = opendir(procfs_path);
1220 if (!d)
1221 return -errno;
1222
1223 if (ret_path)
1224 *ret_path = TAKE_PTR(p);
1225
1226 *ret_dir = d;
1227 return 0;
1228}
1229
d2bcd0ba
LP
1230int chase_symlinks_and_stat(
1231 const char *path,
1232 const char *root,
1233 unsigned chase_flags,
1234 char **ret_path,
a5648b80
ZJS
1235 struct stat *ret_stat,
1236 int *ret_fd) {
d2bcd0ba
LP
1237
1238 _cleanup_close_ int path_fd = -1;
1239 _cleanup_free_ char *p = NULL;
a5648b80 1240 int r;
d2bcd0ba
LP
1241
1242 assert(path);
1243 assert(ret_stat);
1244
1245 if (chase_flags & CHASE_NONEXISTENT)
1246 return -EINVAL;
1247
1248 if (empty_or_root(root) && !ret_path && (chase_flags & (CHASE_NO_AUTOFS|CHASE_SAFE)) == 0) {
1249 /* Shortcut this call if none of the special features of this call are requested */
1250 if (stat(path, ret_stat) < 0)
1251 return -errno;
1252
1253 return 1;
1254 }
1255
a5648b80
ZJS
1256 r = chase_symlinks(path, root, chase_flags, ret_path ? &p : NULL, &path_fd);
1257 if (r < 0)
1258 return r;
1259 assert(path_fd >= 0);
d2bcd0ba
LP
1260
1261 if (fstat(path_fd, ret_stat) < 0)
1262 return -errno;
1263
1264 if (ret_path)
1265 *ret_path = TAKE_PTR(p);
a5648b80
ZJS
1266 if (ret_fd)
1267 *ret_fd = TAKE_FD(path_fd);
d2bcd0ba
LP
1268
1269 return 1;
1270}
1271
57a4359e 1272int access_fd(int fd, int mode) {
fbd0b64f 1273 char p[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
57a4359e
LP
1274
1275 /* Like access() but operates on an already open fd */
1276
1277 xsprintf(p, "/proc/self/fd/%i", fd);
4265a66a
LP
1278 if (access(p, mode) < 0) {
1279 if (errno != ENOENT)
1280 return -errno;
57a4359e 1281
4265a66a
LP
1282 /* ENOENT can mean two things: that the fd does not exist or that /proc is not mounted. Let's
1283 * make things debuggable and distinguish the two. */
1284
1285 if (proc_mounted() == 0)
1286 return -ENOSYS; /* /proc is not available or not set up properly, we're most likely in some chroot
1287 * environment. */
1288
1289 return -EBADF; /* The directory exists, hence it's the fd that doesn't. */
1290 }
1291
1292 return 0;
57a4359e 1293}
43767d9d 1294
627d2bac
ZJS
1295void unlink_tempfilep(char (*p)[]) {
1296 /* If the file is created with mkstemp(), it will (almost always)
1297 * change the suffix. Treat this as a sign that the file was
1298 * successfully created. We ignore both the rare case where the
1299 * original suffix is used and unlink failures. */
1300 if (!endswith(*p, ".XXXXXX"))
69821560 1301 (void) unlink_noerrno(*p);
627d2bac
ZJS
1302}
1303
053e0626 1304int unlinkat_deallocate(int fd, const char *name, UnlinkDeallocateFlags flags) {
43767d9d
LP
1305 _cleanup_close_ int truncate_fd = -1;
1306 struct stat st;
1307 off_t l, bs;
1308
053e0626
LP
1309 assert((flags & ~(UNLINK_REMOVEDIR|UNLINK_ERASE)) == 0);
1310
43767d9d
LP
1311 /* Operates like unlinkat() but also deallocates the file contents if it is a regular file and there's no other
1312 * link to it. This is useful to ensure that other processes that might have the file open for reading won't be
1313 * able to keep the data pinned on disk forever. This call is particular useful whenever we execute clean-up
1314 * jobs ("vacuuming"), where we want to make sure the data is really gone and the disk space released and
1315 * returned to the free pool.
1316 *
1317 * Deallocation is preferably done by FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE (👊) if supported, which means
1318 * the file won't change size. That's a good thing since we shouldn't needlessly trigger SIGBUS in other
1319 * programs that have mmap()ed the file. (The assumption here is that changing file contents to all zeroes
1320 * underneath those programs is the better choice than simply triggering SIGBUS in them which truncation does.)
1321 * However if hole punching is not implemented in the kernel or file system we'll fall back to normal file
1322 * truncation (🔪), as our goal of deallocating the data space trumps our goal of being nice to readers (💐).
1323 *
1324 * Note that we attempt deallocation, but failure to succeed with that is not considered fatal, as long as the
1325 * primary job – to delete the file – is accomplished. */
1326
053e0626 1327 if (!FLAGS_SET(flags, UNLINK_REMOVEDIR)) {
43767d9d
LP
1328 truncate_fd = openat(fd, name, O_WRONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW|O_NONBLOCK);
1329 if (truncate_fd < 0) {
1330
1331 /* If this failed because the file doesn't exist propagate the error right-away. Also,
1332 * AT_REMOVEDIR wasn't set, and we tried to open the file for writing, which means EISDIR is
1333 * returned when this is a directory but we are not supposed to delete those, hence propagate
1334 * the error right-away too. */
1335 if (IN_SET(errno, ENOENT, EISDIR))
1336 return -errno;
1337
1338 if (errno != ELOOP) /* don't complain if this is a symlink */
1339 log_debug_errno(errno, "Failed to open file '%s' for deallocation, ignoring: %m", name);
1340 }
1341 }
1342
053e0626 1343 if (unlinkat(fd, name, FLAGS_SET(flags, UNLINK_REMOVEDIR) ? AT_REMOVEDIR : 0) < 0)
43767d9d
LP
1344 return -errno;
1345
1346 if (truncate_fd < 0) /* Don't have a file handle, can't do more ☹️ */
1347 return 0;
1348
1349 if (fstat(truncate_fd, &st) < 0) {
011723a4 1350 log_debug_errno(errno, "Failed to stat file '%s' for deallocation, ignoring: %m", name);
43767d9d
LP
1351 return 0;
1352 }
1353
053e0626
LP
1354 if (!S_ISREG(st.st_mode))
1355 return 0;
1356
1357 if (FLAGS_SET(flags, UNLINK_ERASE) && st.st_size > 0 && st.st_nlink == 0) {
1358 uint64_t left = st.st_size;
1359 char buffer[64 * 1024];
1360
1361 /* If erasing is requested, let's overwrite the file with random data once before deleting
1362 * it. This isn't going to give you shred(1) semantics, but hopefully should be good enough
1363 * for stuff backed by tmpfs at least.
1364 *
15dd4515 1365 * Note that we only erase like this if the link count of the file is zero. If it is higher it
053e0626
LP
1366 * is still linked by someone else and we'll leave it to them to remove it securely
1367 * eventually! */
1368
1369 random_bytes(buffer, sizeof(buffer));
1370
1371 while (left > 0) {
1372 ssize_t n;
1373
1374 n = write(truncate_fd, buffer, MIN(sizeof(buffer), left));
1375 if (n < 0) {
1376 log_debug_errno(errno, "Failed to erase data in file '%s', ignoring.", name);
1377 break;
1378 }
1379
1380 assert(left >= (size_t) n);
1381 left -= n;
1382 }
1383
1384 /* Let's refresh metadata */
1385 if (fstat(truncate_fd, &st) < 0) {
1386 log_debug_errno(errno, "Failed to stat file '%s' for deallocation, ignoring: %m", name);
1387 return 0;
1388 }
1389 }
1390
1391 /* Don't dallocate if there's nothing to deallocate or if the file is linked elsewhere */
1392 if (st.st_blocks == 0 || st.st_nlink > 0)
43767d9d
LP
1393 return 0;
1394
1395 /* If this is a regular file, it actually took up space on disk and there are no other links it's time to
1396 * punch-hole/truncate this to release the disk space. */
1397
1398 bs = MAX(st.st_blksize, 512);
1399 l = DIV_ROUND_UP(st.st_size, bs) * bs; /* Round up to next block size */
1400
1401 if (fallocate(truncate_fd, FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE, 0, l) >= 0)
1402 return 0; /* Successfully punched a hole! 😊 */
1403
1404 /* Fall back to truncation */
1405 if (ftruncate(truncate_fd, 0) < 0) {
1406 log_debug_errno(errno, "Failed to truncate file to 0, ignoring: %m");
1407 return 0;
1408 }
1409
1410 return 0;
1411}
11b29a96
LP
1412
1413int fsync_directory_of_file(int fd) {
0c462ea4 1414 _cleanup_free_ char *path = NULL;
11b29a96
LP
1415 _cleanup_close_ int dfd = -1;
1416 int r;
1417
1418 r = fd_verify_regular(fd);
1419 if (r < 0)
1420 return r;
1421
1422 r = fd_get_path(fd, &path);
3ceae1bc 1423 if (r < 0) {
b8b846d7
LP
1424 log_debug_errno(r, "Failed to query /proc/self/fd/%d%s: %m",
1425 fd,
8fe8f3aa 1426 r == -ENOSYS ? ", ignoring" : "");
3ceae1bc 1427
8fe8f3aa 1428 if (r == -ENOSYS)
3ceae1bc
ZJS
1429 /* If /proc is not available, we're most likely running in some
1430 * chroot environment, and syncing the directory is not very
1431 * important in that case. Let's just silently do nothing. */
1432 return 0;
1433
11b29a96 1434 return r;
3ceae1bc 1435 }
11b29a96
LP
1436
1437 if (!path_is_absolute(path))
1438 return -EINVAL;
1439
0c462ea4 1440 dfd = open_parent(path, O_CLOEXEC, 0);
11b29a96 1441 if (dfd < 0)
0c462ea4 1442 return dfd;
11b29a96
LP
1443
1444 if (fsync(dfd) < 0)
1445 return -errno;
1446
1447 return 0;
1448}
ef8becfa 1449
63d59b8d
LP
1450int fsync_full(int fd) {
1451 int r, q;
1452
1453 /* Sync both the file and the directory */
1454
1455 r = fsync(fd) < 0 ? -errno : 0;
1456 q = fsync_directory_of_file(fd);
1457
1458 return r < 0 ? r : q;
1459}
1460
36695e88
LP
1461int fsync_path_at(int at_fd, const char *path) {
1462 _cleanup_close_ int opened_fd = -1;
1463 int fd;
1464
1465 if (isempty(path)) {
1466 if (at_fd == AT_FDCWD) {
1467 opened_fd = open(".", O_RDONLY|O_DIRECTORY|O_CLOEXEC);
1468 if (opened_fd < 0)
1469 return -errno;
1470
1471 fd = opened_fd;
1472 } else
1473 fd = at_fd;
1474 } else {
1475
1476 opened_fd = openat(at_fd, path, O_RDONLY|O_CLOEXEC);
1477 if (opened_fd < 0)
1478 return -errno;
1479
1480 fd = opened_fd;
1481 }
1482
1483 if (fsync(fd) < 0)
1484 return -errno;
1485
1486 return 0;
1487}
1488
71f51416
LP
1489int syncfs_path(int atfd, const char *path) {
1490 _cleanup_close_ int fd = -1;
1491
1492 assert(path);
1493
1494 fd = openat(atfd, path, O_CLOEXEC|O_RDONLY|O_NONBLOCK);
1495 if (fd < 0)
1496 return -errno;
1497
1498 if (syncfs(fd) < 0)
1499 return -errno;
1500
1501 return 0;
1502}
1503
ef8becfa
LP
1504int open_parent(const char *path, int flags, mode_t mode) {
1505 _cleanup_free_ char *parent = NULL;
1506 int fd;
1507
1508 if (isempty(path))
1509 return -EINVAL;
1510 if (path_equal(path, "/")) /* requesting the parent of the root dir is fishy, let's prohibit that */
1511 return -EINVAL;
1512
1513 parent = dirname_malloc(path);
1514 if (!parent)
1515 return -ENOMEM;
1516
1517 /* Let's insist on O_DIRECTORY since the parent of a file or directory is a directory. Except if we open an
1518 * O_TMPFILE file, because in that case we are actually create a regular file below the parent directory. */
1519
0c21dafb 1520 if (FLAGS_SET(flags, O_PATH))
ef8becfa 1521 flags |= O_DIRECTORY;
0c21dafb 1522 else if (!FLAGS_SET(flags, O_TMPFILE))
ef8becfa
LP
1523 flags |= O_DIRECTORY|O_RDONLY;
1524
1525 fd = open(parent, flags, mode);
1526 if (fd < 0)
1527 return -errno;
1528
1529 return fd;
1530}
ed9c0851 1531
622e1cdb
LP
1532static int blockdev_is_encrypted(const char *sysfs_path, unsigned depth_left) {
1533 _cleanup_free_ char *p = NULL, *uuids = NULL;
1534 _cleanup_closedir_ DIR *d = NULL;
1535 int r, found_encrypted = false;
1536
1537 assert(sysfs_path);
1538
1539 if (depth_left == 0)
1540 return -EINVAL;
1541
1542 p = path_join(sysfs_path, "dm/uuid");
1543 if (!p)
1544 return -ENOMEM;
1545
1546 r = read_one_line_file(p, &uuids);
1547 if (r != -ENOENT) {
1548 if (r < 0)
1549 return r;
1550
1551 /* The DM device's uuid attribute is prefixed with "CRYPT-" if this is a dm-crypt device. */
1552 if (startswith(uuids, "CRYPT-"))
1553 return true;
1554 }
1555
1556 /* Not a dm-crypt device itself. But maybe it is on top of one? Follow the links in the "slaves/"
1557 * subdir. */
1558
1559 p = mfree(p);
1560 p = path_join(sysfs_path, "slaves");
1561 if (!p)
1562 return -ENOMEM;
1563
1564 d = opendir(p);
1565 if (!d) {
6b000af4 1566 if (errno == ENOENT) /* Doesn't have underlying devices */
622e1cdb
LP
1567 return false;
1568
1569 return -errno;
1570 }
1571
1572 for (;;) {
1573 _cleanup_free_ char *q = NULL;
1574 struct dirent *de;
1575
1576 errno = 0;
1577 de = readdir_no_dot(d);
1578 if (!de) {
1579 if (errno != 0)
1580 return -errno;
1581
6b000af4 1582 break; /* No more underlying devices */
622e1cdb
LP
1583 }
1584
1585 q = path_join(p, de->d_name);
1586 if (!q)
1587 return -ENOMEM;
1588
1589 r = blockdev_is_encrypted(q, depth_left - 1);
1590 if (r < 0)
1591 return r;
1592 if (r == 0) /* we found one that is not encrypted? then propagate that immediately */
1593 return false;
1594
1595 found_encrypted = true;
1596 }
1597
1598 return found_encrypted;
1599}
1600
ed9c0851 1601int path_is_encrypted(const char *path) {
622e1cdb 1602 char p[SYS_BLOCK_PATH_MAX(NULL)];
ed9c0851
LP
1603 dev_t devt;
1604 int r;
1605
1606 r = get_block_device(path, &devt);
1607 if (r < 0)
1608 return r;
1609 if (r == 0) /* doesn't have a block device */
1610 return false;
1611
622e1cdb 1612 xsprintf_sys_block_path(p, NULL, devt);
ed9c0851 1613
622e1cdb 1614 return blockdev_is_encrypted(p, 10 /* safety net: maximum recursion depth */);
ed9c0851 1615}
10981424
LP
1616
1617int conservative_rename(
1618 int olddirfd, const char *oldpath,
1619 int newdirfd, const char *newpath) {
1620
1621 _cleanup_close_ int old_fd = -1, new_fd = -1;
1622 struct stat old_stat, new_stat;
1623
1624 /* Renames the old path to thew new path, much like renameat() — except if both are regular files and
1625 * have the exact same contents and basic file attributes already. In that case remove the new file
1626 * instead. This call is useful for reducing inotify wakeups on files that are updated but don't
1627 * actually change. This function is written in a style that we rather rename too often than suppress
1628 * too much. i.e. whenever we are in doubt we rather rename than fail. After all reducing inotify
1629 * events is an optimization only, not more. */
1630
1631 old_fd = openat(olddirfd, oldpath, O_CLOEXEC|O_RDONLY|O_NOCTTY|O_NOFOLLOW);
1632 if (old_fd < 0)
1633 goto do_rename;
1634
1635 new_fd = openat(newdirfd, newpath, O_CLOEXEC|O_RDONLY|O_NOCTTY|O_NOFOLLOW);
1636 if (new_fd < 0)
1637 goto do_rename;
1638
1639 if (fstat(old_fd, &old_stat) < 0)
1640 goto do_rename;
1641
1642 if (!S_ISREG(old_stat.st_mode))
1643 goto do_rename;
1644
1645 if (fstat(new_fd, &new_stat) < 0)
1646 goto do_rename;
1647
1648 if (new_stat.st_ino == old_stat.st_ino &&
1649 new_stat.st_dev == old_stat.st_dev)
1650 goto is_same;
1651
1652 if (old_stat.st_mode != new_stat.st_mode ||
1653 old_stat.st_size != new_stat.st_size ||
1654 old_stat.st_uid != new_stat.st_uid ||
1655 old_stat.st_gid != new_stat.st_gid)
1656 goto do_rename;
1657
1658 for (;;) {
1659 char buf1[16*1024];
1660 char buf2[sizeof(buf1) + 1];
1661 ssize_t l1, l2;
1662
1663 l1 = read(old_fd, buf1, sizeof(buf1));
1664 if (l1 < 0)
1665 goto do_rename;
1666
1667 l2 = read(new_fd, buf2, l1 + 1);
1668 if (l1 != l2)
1669 goto do_rename;
1670
1671 if (l1 == 0) /* EOF on both! And everything's the same so far, yay! */
1672 break;
1673
1674 if (memcmp(buf1, buf2, l1) != 0)
1675 goto do_rename;
1676 }
1677
1678is_same:
1679 /* Everything matches? Then don't rename, instead remove the source file, and leave the existing
1680 * destination in place */
1681
1682 if (unlinkat(olddirfd, oldpath, 0) < 0)
1683 goto do_rename;
1684
1685 return 0;
1686
1687do_rename:
1688 if (renameat(olddirfd, oldpath, newdirfd, newpath) < 0)
1689 return -errno;
1690
1691 return 1;
1692}