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