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