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