]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/fs-util.c
Merge pull request #31754 from YHNdnzj/journal-fd-namespace
[thirdparty/systemd.git] / src / basic / fs-util.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
f4f15635 2
11c3a366
TA
3#include <errno.h>
4#include <stddef.h>
11c3a366 5#include <stdlib.h>
2646b86d 6#include <sys/file.h>
1c73b069 7#include <linux/falloc.h>
655f2da0 8#include <linux/magic.h>
11c3a366
TA
9#include <unistd.h>
10
b5efdb8a 11#include "alloc-util.h"
bc6a6130 12#include "btrfs.h"
f4f15635
LP
13#include "dirent-util.h"
14#include "fd-util.h"
ed9c0851 15#include "fileio.h"
f4f15635 16#include "fs-util.h"
68def5a9 17#include "hostname-util.h"
420d2e31 18#include "label.h"
2646b86d 19#include "lock-util.h"
11c3a366
TA
20#include "log.h"
21#include "macro.h"
0499585f 22#include "missing_fcntl.h"
f5947a5e
YW
23#include "missing_fs.h"
24#include "missing_syscall.h"
93cc7779
TA
25#include "mkdir.h"
26#include "parse-util.h"
27#include "path-util.h"
dccca82b 28#include "process-util.h"
053e0626 29#include "random-util.h"
4c54768c 30#include "ratelimit.h"
34a8f081 31#include "stat-util.h"
430fbf8e 32#include "stdio-util.h"
f4f15635
LP
33#include "string-util.h"
34#include "strv.h"
93cc7779 35#include "time-util.h"
e4de7287 36#include "tmpfile-util.h"
7c248223 37#include "umask-util.h"
ee104e11 38#include "user-util.h"
f4f15635 39
f4f15635 40int rmdir_parents(const char *path, const char *stop) {
4e046c5c
YW
41 char *p;
42 int r;
f4f15635
LP
43
44 assert(path);
45 assert(stop);
46
4e046c5c
YW
47 if (!path_is_safe(path))
48 return -EINVAL;
f4f15635 49
4e046c5c
YW
50 if (!path_is_safe(stop))
51 return -EINVAL;
f4f15635 52
2f82562b 53 p = strdupa_safe(path);
f4f15635 54
4e046c5c
YW
55 for (;;) {
56 char *slash = NULL;
f4f15635 57
4e046c5c
YW
58 /* skip the last component. */
59 r = path_find_last_component(p, /* accept_dot_dot= */ false, (const char **) &slash, NULL);
60 if (r <= 0)
61 return r;
62 if (slash == p)
63 return 0;
f4f15635 64
4e046c5c
YW
65 assert(*slash == '/');
66 *slash = '\0';
f4f15635 67
4e046c5c 68 if (path_startswith_full(stop, p, /* accept_dot_dot= */ false))
f4f15635 69 return 0;
f4f15635 70
4e046c5c
YW
71 if (rmdir(p) < 0 && errno != ENOENT)
72 return -errno;
f4f15635 73 }
f4f15635
LP
74}
75
f4f15635 76int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
2f15b625 77 int r;
f4f15635 78
2f15b625
LP
79 /* Try the ideal approach first */
80 if (renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE) >= 0)
f4f15635
LP
81 return 0;
82
2f15b625
LP
83 /* renameat2() exists since Linux 3.15, btrfs and FAT added support for it later. If it is not implemented,
84 * fall back to a different method. */
62e10065 85 if (!ERRNO_IS_NOT_SUPPORTED(errno) && errno != EINVAL)
f4f15635
LP
86 return -errno;
87
2f15b625
LP
88 /* Let's try to use linkat()+unlinkat() as fallback. This doesn't work on directories and on some file systems
89 * that do not support hard links (such as FAT, most prominently), but for files it's pretty close to what we
90 * want — though not atomic (i.e. for a short period both the new and the old filename will exist). */
91 if (linkat(olddirfd, oldpath, newdirfd, newpath, 0) >= 0) {
92
7c248223
LP
93 r = RET_NERRNO(unlinkat(olddirfd, oldpath, 0));
94 if (r < 0) {
2f15b625
LP
95 (void) unlinkat(newdirfd, newpath, 0);
96 return r;
97 }
98
99 return 0;
f4f15635
LP
100 }
101
62e10065 102 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !IN_SET(errno, EINVAL, EPERM)) /* FAT returns EPERM on link()… */
f4f15635
LP
103 return -errno;
104
2aed63f4 105 /* OK, neither RENAME_NOREPLACE nor linkat()+unlinkat() worked. Let's then fall back to the racy TOCTOU
2f15b625
LP
106 * vulnerable accessat(F_OK) check followed by classic, replacing renameat(), we have nothing better. */
107
108 if (faccessat(newdirfd, newpath, F_OK, AT_SYMLINK_NOFOLLOW) >= 0)
109 return -EEXIST;
110 if (errno != ENOENT)
111 return -errno;
112
7c248223 113 return RET_NERRNO(renameat(olddirfd, oldpath, newdirfd, newpath));
f4f15635
LP
114}
115
116int readlinkat_malloc(int fd, const char *p, char **ret) {
db220032 117 size_t l = PATH_MAX;
f4f15635 118
e4c094c0
YW
119 assert(fd >= 0 || fd == AT_FDCWD);
120
121 if (fd < 0 && isempty(p))
122 return -EISDIR; /* In this case, the fd points to the current working directory, and is
123 * definitely not a symlink. Let's return earlier. */
f4f15635
LP
124
125 for (;;) {
db220032 126 _cleanup_free_ char *c = NULL;
f4f15635
LP
127 ssize_t n;
128
db220032 129 c = new(char, l+1);
f4f15635
LP
130 if (!c)
131 return -ENOMEM;
132
e4c094c0 133 n = readlinkat(fd, strempty(p), c, l);
db220032
LP
134 if (n < 0)
135 return -errno;
f4f15635 136
db220032 137 if ((size_t) n < l) {
f4f15635 138 c[n] = 0;
aed3c5ec
LP
139
140 if (ret)
141 *ret = TAKE_PTR(c);
142
f4f15635
LP
143 return 0;
144 }
145
db220032
LP
146 if (l > (SSIZE_MAX-1)/2) /* readlinkat() returns an ssize_t, and we want an extra byte for a
147 * trailing NUL, hence do an overflow check relative to SSIZE_MAX-1
148 * here */
149 return -EFBIG;
150
f4f15635
LP
151 l *= 2;
152 }
153}
154
155int readlink_malloc(const char *p, char **ret) {
156 return readlinkat_malloc(AT_FDCWD, p, ret);
157}
158
159int readlink_value(const char *p, char **ret) {
bb60956b 160 _cleanup_free_ char *link = NULL, *name = NULL;
f4f15635
LP
161 int r;
162
ce8394f9
YW
163 assert(p);
164 assert(ret);
165
f4f15635
LP
166 r = readlink_malloc(p, &link);
167 if (r < 0)
168 return r;
169
bb60956b
YW
170 r = path_extract_filename(link, &name);
171 if (r < 0)
172 return r;
173 if (r == O_DIRECTORY)
174 return -EINVAL;
175
176 *ret = TAKE_PTR(name);
177 return 0;
f4f15635
LP
178}
179
162f6477 180int readlink_and_make_absolute(const char *p, char **ret) {
f4f15635 181 _cleanup_free_ char *target = NULL;
162f6477 182 int r;
f4f15635
LP
183
184 assert(p);
162f6477 185 assert(ret);
f4f15635 186
162f6477
LP
187 r = readlink_malloc(p, &target);
188 if (r < 0)
189 return r;
f4f15635 190
162f6477 191 return file_in_same_dir(p, target, ret);
f4f15635
LP
192}
193
55451417 194int chmod_and_chown_at(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid) {
254d1313 195 _cleanup_close_ int fd = -EBADF;
30ff18d8 196
7d000133
DDM
197 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
198
55451417
DDM
199 if (path) {
200 /* Let's acquire an O_PATH fd, as precaution to change mode/owner on the same file */
201 fd = openat(dir_fd, path, O_PATH|O_CLOEXEC|O_NOFOLLOW);
202 if (fd < 0)
203 return -errno;
340bc268
YW
204 dir_fd = fd;
205
206 } else if (dir_fd == AT_FDCWD) {
207 /* Let's acquire an O_PATH fd of the current directory */
208 fd = openat(dir_fd, ".", O_PATH|O_CLOEXEC|O_NOFOLLOW|O_DIRECTORY);
209 if (fd < 0)
210 return -errno;
211 dir_fd = fd;
55451417 212 }
de321f52 213
340bc268 214 return fchmod_and_chown(dir_fd, mode, uid, gid);
b8da477e
YW
215}
216
0520564d 217int fchmod_and_chown_with_fallback(int fd, const char *path, mode_t mode, uid_t uid, gid_t gid) {
2dbb7e94 218 bool do_chown, do_chmod;
30ff18d8 219 struct stat st;
dee00c19 220 int r;
30ff18d8 221
2dbb7e94
LP
222 /* Change ownership and access mode of the specified fd. Tries to do so safely, ensuring that at no
223 * point in time the access mode is above the old access mode under the old ownership or the new
224 * access mode under the new ownership. Note: this call tries hard to leave the access mode
225 * unaffected if the uid/gid is changed, i.e. it undoes implicit suid/sgid dropping the kernel does
226 * on chown().
227 *
0520564d
ZJS
228 * This call is happy with O_PATH fds.
229 *
230 * If path is given, allow a fallback path which does not use /proc/self/fd/. On any normal system
231 * /proc will be mounted, but in certain improperly assembled environments it might not be. This is
232 * less secure (potential TOCTOU), so should only be used after consideration. */
b8da477e 233
71ec74d1 234 if (fstat(fd, &st) < 0)
2dbb7e94 235 return -errno;
de321f52 236
2dbb7e94
LP
237 do_chown =
238 (uid != UID_INVALID && st.st_uid != uid) ||
239 (gid != GID_INVALID && st.st_gid != gid);
de321f52 240
2dbb7e94
LP
241 do_chmod =
242 !S_ISLNK(st.st_mode) && /* chmod is not defined on symlinks */
243 ((mode != MODE_INVALID && ((st.st_mode ^ mode) & 07777) != 0) ||
244 do_chown); /* If we change ownership, make sure we reset the mode afterwards, since chown()
245 * modifies the access mode too */
30ff18d8 246
2dbb7e94
LP
247 if (mode == MODE_INVALID)
248 mode = st.st_mode; /* If we only shall do a chown(), save original mode, since chown() might break it. */
249 else if ((mode & S_IFMT) != 0 && ((mode ^ st.st_mode) & S_IFMT) != 0)
250 return -EINVAL; /* insist on the right file type if it was specified */
de321f52 251
2dbb7e94
LP
252 if (do_chown && do_chmod) {
253 mode_t minimal = st.st_mode & mode; /* the subset of the old and the new mask */
30ff18d8 254
dee00c19
LP
255 if (((minimal ^ st.st_mode) & 07777) != 0) {
256 r = fchmod_opath(fd, minimal & 07777);
0520564d
ZJS
257 if (r < 0) {
258 if (!path || r != -ENOSYS)
259 return r;
260
261 /* Fallback path which doesn't use /proc/self/fd/. */
262 if (chmod(path, minimal & 07777) < 0)
263 return -errno;
264 }
dee00c19 265 }
de321f52 266 }
b8da477e 267
2dbb7e94 268 if (do_chown)
71ec74d1 269 if (fchownat(fd, "", uid, gid, AT_EMPTY_PATH) < 0)
2dbb7e94 270 return -errno;
30ff18d8 271
dee00c19
LP
272 if (do_chmod) {
273 r = fchmod_opath(fd, mode & 07777);
0520564d
ZJS
274 if (r < 0) {
275 if (!path || r != -ENOSYS)
276 return r;
277
278 /* Fallback path which doesn't use /proc/self/fd/. */
279 if (chmod(path, mode & 07777) < 0)
280 return -errno;
281 }
dee00c19 282 }
30ff18d8 283
2dbb7e94 284 return do_chown || do_chmod;
f4f15635
LP
285}
286
f4f15635 287int fchmod_umask(int fd, mode_t m) {
7c248223 288 _cleanup_umask_ mode_t u = umask(0777);
f4f15635 289
7c248223 290 return RET_NERRNO(fchmod(fd, m & (~u)));
f4f15635
LP
291}
292
4dfaa528 293int fchmod_opath(int fd, mode_t m) {
4dfaa528 294 /* This function operates also on fd that might have been opened with
adecfb3b
AM
295 * O_PATH. The tool set we have is non-intuitive:
296 * - fchmod(2) only operates on open files (i. e., fds with an open file description);
297 * - fchmodat(2) does not have a flag arg like fchownat(2) does, so no way to pass AT_EMPTY_PATH;
298 * + it should not be confused with the libc fchmodat(3) interface, which adds 4th flag argument,
299 * but does not support AT_EMPTY_PATH (only supports AT_SYMLINK_NOFOLLOW);
300 * - fchmodat2(2) supports all the AT_* flags, but is still very recent.
301 *
302 * We try to use fchmodat2(), and, if it is not supported, resort
303 * to the /proc/self/fd dance. */
304
305 assert(fd >= 0);
306
307 if (fchmodat2(fd, "", m, AT_EMPTY_PATH) >= 0)
308 return 0;
309 if (!IN_SET(errno, ENOSYS, EPERM)) /* Some container managers block unknown syscalls with EPERM */
310 return -errno;
4dfaa528 311
ddb6eeaf 312 if (chmod(FORMAT_PROC_FD_PATH(fd), m) < 0) {
f8606626
LP
313 if (errno != ENOENT)
314 return -errno;
315
316 if (proc_mounted() == 0)
317 return -ENOSYS; /* if we have no /proc/, the concept is not implementable */
318
319 return -ENOENT;
320 }
4dfaa528
FB
321
322 return 0;
323}
324
f25bff5e 325int futimens_opath(int fd, const struct timespec ts[2]) {
150231d2 326 /* Similar to fchmod_opath() but for futimens() */
f25bff5e 327
ddb6eeaf 328 if (utimensat(AT_FDCWD, FORMAT_PROC_FD_PATH(fd), ts, 0) < 0) {
f25bff5e
LP
329 if (errno != ENOENT)
330 return -errno;
331
332 if (proc_mounted() == 0)
333 return -ENOSYS; /* if we have no /proc/, the concept is not implementable */
334
335 return -ENOENT;
336 }
337
338 return 0;
339}
340
22ed4a6d
LP
341int stat_warn_permissions(const char *path, const struct stat *st) {
342 assert(path);
343 assert(st);
f4f15635 344
b6cceaae 345 /* Don't complain if we are reading something that is not a file, for example /dev/null */
22ed4a6d 346 if (!S_ISREG(st->st_mode))
b6cceaae
LP
347 return 0;
348
22ed4a6d 349 if (st->st_mode & 0111)
f4f15635
LP
350 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
351
22ed4a6d 352 if (st->st_mode & 0002)
f4f15635
LP
353 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
354
22ed4a6d 355 if (getpid_cached() == 1 && (st->st_mode & 0044) != 0044)
f4f15635
LP
356 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);
357
358 return 0;
359}
360
22ed4a6d
LP
361int fd_warn_permissions(const char *path, int fd) {
362 struct stat st;
363
364 assert(path);
365 assert(fd >= 0);
366
367 if (fstat(fd, &st) < 0)
368 return -errno;
369
370 return stat_warn_permissions(path, &st);
371}
372
f4f15635 373int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
254d1313 374 _cleanup_close_ int fd = -EBADF;
b71dbc6b 375 int r, ret;
f4f15635
LP
376
377 assert(path);
378
9e3fa6e8
LP
379 /* Note that touch_file() does not follow symlinks: if invoked on an existing symlink, then it is the symlink
380 * itself which is updated, not its target
381 *
382 * Returns the first error we encounter, but tries to apply as much as possible. */
f4f15635 383
9e3fa6e8
LP
384 if (parents)
385 (void) mkdir_parents(path, 0755);
386
387 /* Initially, we try to open the node with O_PATH, so that we get a reference to the node. This is useful in
388 * case the path refers to an existing device or socket node, as we can open it successfully in all cases, and
389 * won't trigger any driver magic or so. */
390 fd = open(path, O_PATH|O_CLOEXEC|O_NOFOLLOW);
391 if (fd < 0) {
392 if (errno != ENOENT)
f4f15635 393 return -errno;
f4f15635 394
9e3fa6e8
LP
395 /* if the node doesn't exist yet, we create it, but with O_EXCL, so that we only create a regular file
396 * here, and nothing else */
397 fd = open(path, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC, IN_SET(mode, 0, MODE_INVALID) ? 0644 : mode);
398 if (fd < 0)
f4f15635
LP
399 return -errno;
400 }
401
9e3fa6e8
LP
402 /* Let's make a path from the fd, and operate on that. With this logic, we can adjust the access mode,
403 * ownership and time of the file node in all cases, even if the fd refers to an O_PATH object — which is
404 * something fchown(), fchmod(), futimensat() don't allow. */
4b3b5bc7 405 ret = fchmod_and_chown(fd, mode, uid, gid);
9e3fa6e8 406
f4f15635
LP
407 if (stamp != USEC_INFINITY) {
408 struct timespec ts[2];
409
410 timespec_store(&ts[0], stamp);
411 ts[1] = ts[0];
b5794711 412 r = futimens_opath(fd, ts);
f4f15635 413 } else
b5794711 414 r = futimens_opath(fd, NULL);
9e3fa6e8 415 if (r < 0 && ret >= 0)
b5794711 416 return r;
f4f15635 417
9e3fa6e8 418 return ret;
f4f15635
LP
419}
420
6c9c51e5
YW
421int symlink_idempotent(const char *from, const char *to, bool make_relative) {
422 _cleanup_free_ char *relpath = NULL;
f4f15635
LP
423 int r;
424
425 assert(from);
426 assert(to);
427
6c9c51e5 428 if (make_relative) {
449375d2 429 r = path_make_relative_parent(to, from, &relpath);
6c9c51e5
YW
430 if (r < 0)
431 return r;
432
433 from = relpath;
434 }
435
f4f15635 436 if (symlink(from, to) < 0) {
77b79723
LP
437 _cleanup_free_ char *p = NULL;
438
f4f15635
LP
439 if (errno != EEXIST)
440 return -errno;
441
442 r = readlink_malloc(to, &p);
77b79723
LP
443 if (r == -EINVAL) /* Not a symlink? In that case return the original error we encountered: -EEXIST */
444 return -EEXIST;
445 if (r < 0) /* Any other error? In that case propagate it as is */
f4f15635
LP
446 return r;
447
77b79723
LP
448 if (!streq(p, from)) /* Not the symlink we want it to be? In that case, propagate the original -EEXIST */
449 return -EEXIST;
f4f15635
LP
450 }
451
452 return 0;
453}
454
da9dd029 455int symlinkat_atomic_full(const char *from, int atfd, const char *to, bool make_relative) {
590d8100 456 _cleanup_free_ char *relpath = NULL, *t = NULL;
f4f15635
LP
457 int r;
458
459 assert(from);
460 assert(to);
461
590d8100
YW
462 if (make_relative) {
463 r = path_make_relative_parent(to, from, &relpath);
464 if (r < 0)
465 return r;
466
467 from = relpath;
468 }
469
f4f15635
LP
470 r = tempfn_random(to, NULL, &t);
471 if (r < 0)
472 return r;
473
da9dd029 474 if (symlinkat(from, atfd, t) < 0)
f4f15635
LP
475 return -errno;
476
da9dd029
LP
477 r = RET_NERRNO(renameat(atfd, t, atfd, to));
478 if (r < 0) {
479 (void) unlinkat(atfd, t, 0);
480 return r;
f4f15635
LP
481 }
482
483 return 0;
484}
485
497ca785 486int mknodat_atomic(int atfd, const char *path, mode_t mode, dev_t dev) {
f4f15635
LP
487 _cleanup_free_ char *t = NULL;
488 int r;
489
490 assert(path);
491
492 r = tempfn_random(path, NULL, &t);
493 if (r < 0)
494 return r;
495
497ca785 496 if (mknodat(atfd, t, mode, dev) < 0)
f4f15635
LP
497 return -errno;
498
497ca785
LP
499 r = RET_NERRNO(renameat(atfd, t, atfd, path));
500 if (r < 0) {
501 (void) unlinkat(atfd, t, 0);
502 return r;
f4f15635
LP
503 }
504
505 return 0;
506}
507
4f477796 508int mkfifoat_atomic(int atfd, const char *path, mode_t mode) {
f4f15635
LP
509 _cleanup_free_ char *t = NULL;
510 int r;
511
512 assert(path);
513
4f477796 514 /* We're only interested in the (random) filename. */
f4f15635
LP
515 r = tempfn_random(path, NULL, &t);
516 if (r < 0)
517 return r;
518
4f477796 519 if (mkfifoat(atfd, t, mode) < 0)
4fe3828c 520 return -errno;
4fe3828c 521
4f477796
LP
522 r = RET_NERRNO(renameat(atfd, t, atfd, path));
523 if (r < 0) {
524 (void) unlinkat(atfd, t, 0);
4fe3828c 525 return r;
f4f15635
LP
526 }
527
528 return 0;
529}
530
531int get_files_in_directory(const char *path, char ***list) {
319a4f4b 532 _cleanup_strv_free_ char **l = NULL;
f4f15635 533 _cleanup_closedir_ DIR *d = NULL;
319a4f4b 534 size_t n = 0;
f4f15635
LP
535
536 assert(path);
537
538 /* Returns all files in a directory in *list, and the number
539 * of files as return value. If list is NULL returns only the
540 * number. */
541
542 d = opendir(path);
543 if (!d)
544 return -errno;
545
8fb3f009 546 FOREACH_DIRENT_ALL(de, d, return -errno) {
f4f15635
LP
547 if (!dirent_is_file(de))
548 continue;
549
550 if (list) {
551 /* one extra slot is needed for the terminating NULL */
319a4f4b 552 if (!GREEDY_REALLOC(l, n + 2))
f4f15635
LP
553 return -ENOMEM;
554
555 l[n] = strdup(de->d_name);
556 if (!l[n])
557 return -ENOMEM;
558
559 l[++n] = NULL;
560 } else
561 n++;
562 }
563
ae2a15bc
LP
564 if (list)
565 *list = TAKE_PTR(l);
f4f15635
LP
566
567 return n;
568}
430fbf8e 569
992e8f22 570static int getenv_tmp_dir(const char **ret_path) {
992e8f22 571 int r, ret = 0;
34a8f081 572
992e8f22 573 assert(ret_path);
34a8f081 574
992e8f22
LP
575 /* We use the same order of environment variables python uses in tempfile.gettempdir():
576 * https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir */
577 FOREACH_STRING(n, "TMPDIR", "TEMP", "TMP") {
578 const char *e;
579
580 e = secure_getenv(n);
581 if (!e)
582 continue;
583 if (!path_is_absolute(e)) {
584 r = -ENOTDIR;
585 goto next;
586 }
99be45a4 587 if (!path_is_normalized(e)) {
992e8f22
LP
588 r = -EPERM;
589 goto next;
590 }
591
592 r = is_dir(e, true);
593 if (r < 0)
594 goto next;
595 if (r == 0) {
596 r = -ENOTDIR;
597 goto next;
598 }
599
600 *ret_path = e;
601 return 1;
602
603 next:
604 /* Remember first error, to make this more debuggable */
605 if (ret >= 0)
606 ret = r;
34a8f081
OW
607 }
608
992e8f22
LP
609 if (ret < 0)
610 return ret;
34a8f081 611
992e8f22
LP
612 *ret_path = NULL;
613 return ret;
614}
34a8f081 615
992e8f22
LP
616static int tmp_dir_internal(const char *def, const char **ret) {
617 const char *e;
618 int r, k;
619
620 assert(def);
621 assert(ret);
622
623 r = getenv_tmp_dir(&e);
624 if (r > 0) {
625 *ret = e;
626 return 0;
627 }
628
629 k = is_dir(def, true);
630 if (k == 0)
631 k = -ENOTDIR;
632 if (k < 0)
633 return r < 0 ? r : k;
634
635 *ret = def;
34a8f081
OW
636 return 0;
637}
638
992e8f22
LP
639int var_tmp_dir(const char **ret) {
640
641 /* Returns the location for "larger" temporary files, that is backed by physical storage if available, and thus
642 * even might survive a boot: /var/tmp. If $TMPDIR (or related environment variables) are set, its value is
643 * returned preferably however. Note that both this function and tmp_dir() below are affected by $TMPDIR,
644 * making it a variable that overrides all temporary file storage locations. */
645
646 return tmp_dir_internal("/var/tmp", ret);
647}
648
649int tmp_dir(const char **ret) {
650
651 /* Similar to var_tmp_dir() above, but returns the location for "smaller" temporary files, which is usually
652 * backed by an in-memory file system: /tmp. */
653
654 return tmp_dir_internal("/tmp", ret);
655}
656
af229d7a
ZJS
657int unlink_or_warn(const char *filename) {
658 if (unlink(filename) < 0 && errno != ENOENT)
659 /* If the file doesn't exist and the fs simply was read-only (in which
660 * case unlink() returns EROFS even if the file doesn't exist), don't
661 * complain */
662 if (errno != EROFS || access(filename, F_OK) >= 0)
663 return log_error_errno(errno, "Failed to remove \"%s\": %m", filename);
664
665 return 0;
666}
667
57a4359e 668int access_fd(int fd, int mode) {
57a4359e
LP
669 /* Like access() but operates on an already open fd */
670
ddb6eeaf 671 if (access(FORMAT_PROC_FD_PATH(fd), mode) < 0) {
4265a66a
LP
672 if (errno != ENOENT)
673 return -errno;
57a4359e 674
4265a66a
LP
675 /* ENOENT can mean two things: that the fd does not exist or that /proc is not mounted. Let's
676 * make things debuggable and distinguish the two. */
677
678 if (proc_mounted() == 0)
679 return -ENOSYS; /* /proc is not available or not set up properly, we're most likely in some chroot
680 * environment. */
681
682 return -EBADF; /* The directory exists, hence it's the fd that doesn't. */
683 }
684
685 return 0;
57a4359e 686}
43767d9d 687
627d2bac
ZJS
688void unlink_tempfilep(char (*p)[]) {
689 /* If the file is created with mkstemp(), it will (almost always)
690 * change the suffix. Treat this as a sign that the file was
691 * successfully created. We ignore both the rare case where the
692 * original suffix is used and unlink failures. */
693 if (!endswith(*p, ".XXXXXX"))
39eb3ffa 694 (void) unlink(*p);
627d2bac
ZJS
695}
696
053e0626 697int unlinkat_deallocate(int fd, const char *name, UnlinkDeallocateFlags flags) {
254d1313 698 _cleanup_close_ int truncate_fd = -EBADF;
43767d9d
LP
699 struct stat st;
700 off_t l, bs;
701
053e0626
LP
702 assert((flags & ~(UNLINK_REMOVEDIR|UNLINK_ERASE)) == 0);
703
43767d9d
LP
704 /* Operates like unlinkat() but also deallocates the file contents if it is a regular file and there's no other
705 * link to it. This is useful to ensure that other processes that might have the file open for reading won't be
706 * able to keep the data pinned on disk forever. This call is particular useful whenever we execute clean-up
707 * jobs ("vacuuming"), where we want to make sure the data is really gone and the disk space released and
708 * returned to the free pool.
709 *
710 * Deallocation is preferably done by FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE (👊) if supported, which means
711 * the file won't change size. That's a good thing since we shouldn't needlessly trigger SIGBUS in other
712 * programs that have mmap()ed the file. (The assumption here is that changing file contents to all zeroes
713 * underneath those programs is the better choice than simply triggering SIGBUS in them which truncation does.)
714 * However if hole punching is not implemented in the kernel or file system we'll fall back to normal file
715 * truncation (🔪), as our goal of deallocating the data space trumps our goal of being nice to readers (💐).
716 *
717 * Note that we attempt deallocation, but failure to succeed with that is not considered fatal, as long as the
718 * primary job – to delete the file – is accomplished. */
719
053e0626 720 if (!FLAGS_SET(flags, UNLINK_REMOVEDIR)) {
43767d9d
LP
721 truncate_fd = openat(fd, name, O_WRONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW|O_NONBLOCK);
722 if (truncate_fd < 0) {
723
724 /* If this failed because the file doesn't exist propagate the error right-away. Also,
725 * AT_REMOVEDIR wasn't set, and we tried to open the file for writing, which means EISDIR is
726 * returned when this is a directory but we are not supposed to delete those, hence propagate
727 * the error right-away too. */
728 if (IN_SET(errno, ENOENT, EISDIR))
729 return -errno;
730
731 if (errno != ELOOP) /* don't complain if this is a symlink */
732 log_debug_errno(errno, "Failed to open file '%s' for deallocation, ignoring: %m", name);
733 }
734 }
735
053e0626 736 if (unlinkat(fd, name, FLAGS_SET(flags, UNLINK_REMOVEDIR) ? AT_REMOVEDIR : 0) < 0)
43767d9d
LP
737 return -errno;
738
739 if (truncate_fd < 0) /* Don't have a file handle, can't do more ☹️ */
740 return 0;
741
742 if (fstat(truncate_fd, &st) < 0) {
011723a4 743 log_debug_errno(errno, "Failed to stat file '%s' for deallocation, ignoring: %m", name);
43767d9d
LP
744 return 0;
745 }
746
053e0626
LP
747 if (!S_ISREG(st.st_mode))
748 return 0;
749
750 if (FLAGS_SET(flags, UNLINK_ERASE) && st.st_size > 0 && st.st_nlink == 0) {
751 uint64_t left = st.st_size;
752 char buffer[64 * 1024];
753
754 /* If erasing is requested, let's overwrite the file with random data once before deleting
755 * it. This isn't going to give you shred(1) semantics, but hopefully should be good enough
756 * for stuff backed by tmpfs at least.
757 *
15dd4515 758 * Note that we only erase like this if the link count of the file is zero. If it is higher it
053e0626
LP
759 * is still linked by someone else and we'll leave it to them to remove it securely
760 * eventually! */
761
762 random_bytes(buffer, sizeof(buffer));
763
764 while (left > 0) {
765 ssize_t n;
766
767 n = write(truncate_fd, buffer, MIN(sizeof(buffer), left));
768 if (n < 0) {
769 log_debug_errno(errno, "Failed to erase data in file '%s', ignoring.", name);
770 break;
771 }
772
773 assert(left >= (size_t) n);
774 left -= n;
775 }
776
777 /* Let's refresh metadata */
778 if (fstat(truncate_fd, &st) < 0) {
779 log_debug_errno(errno, "Failed to stat file '%s' for deallocation, ignoring: %m", name);
780 return 0;
781 }
782 }
783
784 /* Don't dallocate if there's nothing to deallocate or if the file is linked elsewhere */
785 if (st.st_blocks == 0 || st.st_nlink > 0)
43767d9d
LP
786 return 0;
787
788 /* If this is a regular file, it actually took up space on disk and there are no other links it's time to
789 * punch-hole/truncate this to release the disk space. */
790
791 bs = MAX(st.st_blksize, 512);
4dcaab9c 792 l = ROUND_UP(st.st_size, bs); /* Round up to next block size */
43767d9d
LP
793
794 if (fallocate(truncate_fd, FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE, 0, l) >= 0)
795 return 0; /* Successfully punched a hole! 😊 */
796
797 /* Fall back to truncation */
798 if (ftruncate(truncate_fd, 0) < 0) {
799 log_debug_errno(errno, "Failed to truncate file to 0, ignoring: %m");
800 return 0;
801 }
802
803 return 0;
804}
11b29a96 805
14460a8a 806int open_parent_at(int dir_fd, const char *path, int flags, mode_t mode) {
ef8becfa 807 _cleanup_free_ char *parent = NULL;
7c248223 808 int r;
ef8becfa 809
14460a8a
DDM
810 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
811 assert(path);
812
30cdcd62 813 r = path_extract_directory(path, &parent);
14460a8a
DDM
814 if (r == -EDESTADDRREQ) {
815 parent = strdup(".");
816 if (!parent)
817 return -ENOMEM;
818 } else if (r == -EADDRNOTAVAIL) {
819 parent = strdup(path);
820 if (!parent)
821 return -ENOMEM;
822 } else if (r < 0)
30cdcd62 823 return r;
ef8becfa
LP
824
825 /* Let's insist on O_DIRECTORY since the parent of a file or directory is a directory. Except if we open an
826 * O_TMPFILE file, because in that case we are actually create a regular file below the parent directory. */
827
0c21dafb 828 if (FLAGS_SET(flags, O_PATH))
ef8becfa 829 flags |= O_DIRECTORY;
0c21dafb 830 else if (!FLAGS_SET(flags, O_TMPFILE))
ef8becfa
LP
831 flags |= O_DIRECTORY|O_RDONLY;
832
14460a8a 833 return RET_NERRNO(openat(dir_fd, parent, flags, mode));
ef8becfa 834}
ed9c0851 835
10195179 836int conservative_renameat(
10981424
LP
837 int olddirfd, const char *oldpath,
838 int newdirfd, const char *newpath) {
839
254d1313 840 _cleanup_close_ int old_fd = -EBADF, new_fd = -EBADF;
10981424
LP
841 struct stat old_stat, new_stat;
842
737a9edc 843 /* Renames the old path to the new path, much like renameat() — except if both are regular files and
10981424
LP
844 * have the exact same contents and basic file attributes already. In that case remove the new file
845 * instead. This call is useful for reducing inotify wakeups on files that are updated but don't
846 * actually change. This function is written in a style that we rather rename too often than suppress
2657d5bd 847 * too much. I.e. whenever we are in doubt, we rather rename than fail. After all reducing inotify
10981424
LP
848 * events is an optimization only, not more. */
849
850 old_fd = openat(olddirfd, oldpath, O_CLOEXEC|O_RDONLY|O_NOCTTY|O_NOFOLLOW);
851 if (old_fd < 0)
852 goto do_rename;
853
854 new_fd = openat(newdirfd, newpath, O_CLOEXEC|O_RDONLY|O_NOCTTY|O_NOFOLLOW);
855 if (new_fd < 0)
856 goto do_rename;
857
858 if (fstat(old_fd, &old_stat) < 0)
859 goto do_rename;
860
861 if (!S_ISREG(old_stat.st_mode))
862 goto do_rename;
863
864 if (fstat(new_fd, &new_stat) < 0)
865 goto do_rename;
866
a9dac7a6 867 if (stat_inode_same(&new_stat, &old_stat))
10981424
LP
868 goto is_same;
869
870 if (old_stat.st_mode != new_stat.st_mode ||
871 old_stat.st_size != new_stat.st_size ||
872 old_stat.st_uid != new_stat.st_uid ||
873 old_stat.st_gid != new_stat.st_gid)
874 goto do_rename;
875
876 for (;;) {
eff57d1c
LP
877 uint8_t buf1[16*1024];
878 uint8_t buf2[sizeof(buf1)];
10981424
LP
879 ssize_t l1, l2;
880
881 l1 = read(old_fd, buf1, sizeof(buf1));
882 if (l1 < 0)
883 goto do_rename;
884
eff57d1c
LP
885 if (l1 == sizeof(buf1))
886 /* Read the full block, hence read a full block in the other file too */
10981424 887
eff57d1c
LP
888 l2 = read(new_fd, buf2, l1);
889 else {
890 assert((size_t) l1 < sizeof(buf1));
891
892 /* Short read. This hence was the last block in the first file, and then came
893 * EOF. Read one byte more in the second file, so that we can verify we hit EOF there
894 * too. */
895
896 assert((size_t) (l1 + 1) <= sizeof(buf2));
897 l2 = read(new_fd, buf2, l1 + 1);
898 }
899 if (l2 != l1)
900 goto do_rename;
10981424
LP
901
902 if (memcmp(buf1, buf2, l1) != 0)
903 goto do_rename;
eff57d1c
LP
904
905 if ((size_t) l1 < sizeof(buf1)) /* We hit EOF on the first file, and the second file too, hence exit
906 * now. */
907 break;
10981424
LP
908 }
909
910is_same:
911 /* Everything matches? Then don't rename, instead remove the source file, and leave the existing
912 * destination in place */
913
914 if (unlinkat(olddirfd, oldpath, 0) < 0)
915 goto do_rename;
916
917 return 0;
918
919do_rename:
920 if (renameat(olddirfd, oldpath, newdirfd, newpath) < 0)
921 return -errno;
922
923 return 1;
924}
4c54768c
IZ
925
926int posix_fallocate_loop(int fd, uint64_t offset, uint64_t size) {
927 RateLimit rl;
928 int r;
929
930 r = posix_fallocate(fd, offset, size); /* returns positive errnos on error */
931 if (r != EINTR)
932 return -r; /* Let's return negative errnos, like common in our codebase */
933
934 /* On EINTR try a couple of times more, but protect against busy looping
935 * (not more than 16 times per 10s) */
7d1e61ca 936 rl = (const RateLimit) { 10 * USEC_PER_SEC, 16 };
4c54768c
IZ
937 while (ratelimit_below(&rl)) {
938 r = posix_fallocate(fd, offset, size);
939 if (r != EINTR)
940 return -r;
941 }
942
943 return -EINTR;
944}
68def5a9
LP
945
946int parse_cifs_service(
947 const char *s,
948 char **ret_host,
949 char **ret_service,
950 char **ret_path) {
951
952 _cleanup_free_ char *h = NULL, *ss = NULL, *x = NULL;
953 const char *p, *e, *d;
954 char delimiter;
955
956 /* Parses a CIFS service in form of //host/service/path… and splitting it in three parts. The last
957 * part is optional, in which case NULL is returned there. To maximize compatibility syntax with
958 * backslashes instead of slashes is accepted too. */
959
960 if (!s)
961 return -EINVAL;
962
963 p = startswith(s, "//");
964 if (!p) {
965 p = startswith(s, "\\\\");
966 if (!p)
967 return -EINVAL;
968 }
969
970 delimiter = s[0];
971 e = strchr(p, delimiter);
972 if (!e)
973 return -EINVAL;
974
975 h = strndup(p, e - p);
976 if (!h)
977 return -ENOMEM;
978
979 if (!hostname_is_valid(h, 0))
980 return -EINVAL;
981
982 e++;
983
984 d = strchrnul(e, delimiter);
985
986 ss = strndup(e, d - e);
987 if (!ss)
988 return -ENOMEM;
989
990 if (!filename_is_valid(ss))
991 return -EINVAL;
992
993 if (!isempty(d)) {
994 x = strdup(skip_leading_chars(d, CHAR_TO_STR(delimiter)));
995 if (!x)
996 return -EINVAL;
997
998 /* Make sure to convert Windows-style "\" → Unix-style / */
999 for (char *i = x; *i; i++)
1000 if (*i == delimiter)
1001 *i = '/';
1002
1003 if (!path_is_valid(x))
1004 return -EINVAL;
1005
1006 path_simplify(x);
1007 if (!path_is_normalized(x))
1008 return -EINVAL;
1009 }
1010
1011 if (ret_host)
1012 *ret_host = TAKE_PTR(h);
1013 if (ret_service)
1014 *ret_service = TAKE_PTR(ss);
1015 if (ret_path)
1016 *ret_path = TAKE_PTR(x);
1017
1018 return 0;
1019}
c73094f3
LP
1020
1021int open_mkdir_at(int dirfd, const char *path, int flags, mode_t mode) {
254d1313 1022 _cleanup_close_ int fd = -EBADF, parent_fd = -EBADF;
797f6cc5 1023 _cleanup_free_ char *fname = NULL, *parent = NULL;
c73094f3
LP
1024 int r;
1025
1026 /* Creates a directory with mkdirat() and then opens it, in the "most atomic" fashion we can
1027 * do. Guarantees that the returned fd refers to a directory. If O_EXCL is specified will fail if the
1028 * dir already exists. Otherwise will open an existing dir, but only if it is one. */
1029
1030 if (flags & ~(O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_EXCL|O_NOATIME|O_NOFOLLOW|O_PATH))
1031 return -EINVAL;
1032 if ((flags & O_ACCMODE) != O_RDONLY)
1033 return -EINVAL;
1034
1035 /* Note that O_DIRECTORY|O_NOFOLLOW is implied, but we allow specifying it anyway. The following
1036 * flags actually make sense to specify: O_CLOEXEC, O_EXCL, O_NOATIME, O_PATH */
1037
797f6cc5
LP
1038 /* If this is not a valid filename, it's a path. Let's open the parent directory then, so
1039 * that we can pin it, and operate below it. */
1040 r = path_extract_directory(path, &parent);
1041 if (r < 0) {
1042 if (!IN_SET(r, -EDESTADDRREQ, -EADDRNOTAVAIL))
c73094f3 1043 return r;
797f6cc5 1044 } else {
c73094f3
LP
1045 r = path_extract_filename(path, &fname);
1046 if (r < 0)
1047 return r;
1048
1049 parent_fd = openat(dirfd, parent, O_PATH|O_DIRECTORY|O_CLOEXEC);
1050 if (parent_fd < 0)
1051 return -errno;
1052
1053 dirfd = parent_fd;
1054 path = fname;
1055 }
1056
e40b11be 1057 fd = xopenat_full(dirfd, path, flags|O_CREAT|O_DIRECTORY|O_NOFOLLOW, /* xopen_flags = */ 0, mode);
7486f9c3
DDM
1058 if (IN_SET(fd, -ELOOP, -ENOTDIR))
1059 return -EEXIST;
1060 if (fd < 0)
c73094f3 1061 return fd;
c73094f3
LP
1062
1063 return TAKE_FD(fd);
1064}
ca8503f1
LP
1065
1066int openat_report_new(int dirfd, const char *pathname, int flags, mode_t mode, bool *ret_newly_created) {
1067 unsigned attempts = 7;
4d5dacbe 1068 int fd;
ca8503f1
LP
1069
1070 /* Just like openat(), but adds one thing: optionally returns whether we created the file anew or if
b3122369 1071 * it already existed before. This is only relevant if O_CREAT is set without O_EXCL, and thus will
ca8503f1
LP
1072 * shortcut to openat() otherwise */
1073
4d5dacbe 1074 if (!ret_newly_created)
ca8503f1
LP
1075 return RET_NERRNO(openat(dirfd, pathname, flags, mode));
1076
4d5dacbe
LP
1077 if (!FLAGS_SET(flags, O_CREAT) || FLAGS_SET(flags, O_EXCL)) {
1078 fd = openat(dirfd, pathname, flags, mode);
1079 if (fd < 0)
1080 return -errno;
ca8503f1 1081
4d5dacbe
LP
1082 *ret_newly_created = FLAGS_SET(flags, O_CREAT);
1083 return fd;
1084 }
1085
1086 for (;;) {
ca8503f1
LP
1087 /* First, attempt to open without O_CREAT/O_EXCL, i.e. open existing file */
1088 fd = openat(dirfd, pathname, flags & ~(O_CREAT | O_EXCL), mode);
1089 if (fd >= 0) {
1090 *ret_newly_created = false;
1091 return fd;
1092 }
1093 if (errno != ENOENT)
1094 return -errno;
1095
1096 /* So the file didn't exist yet, hence create it with O_CREAT/O_EXCL. */
1097 fd = openat(dirfd, pathname, flags | O_CREAT | O_EXCL, mode);
1098 if (fd >= 0) {
1099 *ret_newly_created = true;
1100 return fd;
1101 }
1102 if (errno != EEXIST)
1103 return -errno;
1104
1105 /* Hmm, so now we got EEXIST? So it apparently exists now? If so, let's try to open again
b3122369 1106 * without the two flags. But let's not spin forever, hence put a limit on things */
ca8503f1
LP
1107
1108 if (--attempts == 0) /* Give up eventually, somebody is playing with us */
1109 return -EEXIST;
1110 }
1111}
7486f9c3 1112
e40b11be 1113int xopenat_full(int dir_fd, const char *path, int open_flags, XOpenFlags xopen_flags, mode_t mode) {
7486f9c3
DDM
1114 _cleanup_close_ int fd = -EBADF;
1115 bool made = false;
1116 int r;
1117
2646b86d 1118 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
2646b86d 1119
9b85e907
LP
1120 /* This is like openat(), but has a few tricks up its sleeves, extending behaviour:
1121 *
1122 * • O_DIRECTORY|O_CREAT is supported, which causes a directory to be created, and immediately
1123 * opened. When used with the XO_SUBVOLUME flag this will even create a btrfs subvolume.
1124 *
1125 * • If O_CREAT is used with XO_LABEL, any created file will be immediately relabelled.
1126 *
1127 * • If the path is specified NULL or empty, behaves like fd_reopen().
1128 */
1129
06ca2db3 1130 if (isempty(path)) {
420d2e31
DDM
1131 assert(!FLAGS_SET(open_flags, O_CREAT|O_EXCL));
1132 return fd_reopen(dir_fd, open_flags & ~O_NOFOLLOW);
06ca2db3
DDM
1133 }
1134
420d2e31
DDM
1135 if (FLAGS_SET(open_flags, O_CREAT) && FLAGS_SET(xopen_flags, XO_LABEL)) {
1136 r = label_ops_pre(dir_fd, path, FLAGS_SET(open_flags, O_DIRECTORY) ? S_IFDIR : S_IFREG);
1137 if (r < 0)
1138 return r;
1139 }
1140
1141 if (FLAGS_SET(open_flags, O_DIRECTORY|O_CREAT)) {
bc6a6130
DDM
1142 if (FLAGS_SET(xopen_flags, XO_SUBVOLUME))
1143 r = btrfs_subvol_make_fallback(dir_fd, path, mode);
1144 else
1145 r = RET_NERRNO(mkdirat(dir_fd, path, mode));
7486f9c3 1146 if (r == -EEXIST) {
420d2e31 1147 if (FLAGS_SET(open_flags, O_EXCL))
7486f9c3
DDM
1148 return -EEXIST;
1149
1150 made = false;
1151 } else if (r < 0)
1152 return r;
1153 else
1154 made = true;
1155
420d2e31
DDM
1156 if (FLAGS_SET(xopen_flags, XO_LABEL)) {
1157 r = label_ops_post(dir_fd, path);
1158 if (r < 0)
1159 return r;
1160 }
1161
1162 open_flags &= ~(O_EXCL|O_CREAT);
1163 xopen_flags &= ~XO_LABEL;
7486f9c3
DDM
1164 }
1165
420d2e31 1166 fd = RET_NERRNO(openat(dir_fd, path, open_flags, mode));
7486f9c3
DDM
1167 if (fd < 0) {
1168 if (IN_SET(fd,
1169 /* We got ENOENT? then someone else immediately removed it after we
1170 * created it. In that case let's return immediately without unlinking
1171 * anything, because there simply isn't anything to unlink anymore. */
1172 -ENOENT,
1173 /* is a symlink? exists already → created by someone else, don't unlink */
1174 -ELOOP,
1175 /* not a directory? exists already → created by someone else, don't unlink */
1176 -ENOTDIR))
1177 return fd;
1178
1179 if (made)
1180 (void) unlinkat(dir_fd, path, AT_REMOVEDIR);
1181
1182 return fd;
1183 }
1184
420d2e31
DDM
1185 if (FLAGS_SET(open_flags, O_CREAT) && FLAGS_SET(xopen_flags, XO_LABEL)) {
1186 r = label_ops_post(dir_fd, path);
1187 if (r < 0)
1188 return r;
1189 }
1190
7486f9c3
DDM
1191 return TAKE_FD(fd);
1192}
2646b86d 1193
e40b11be 1194int xopenat_lock_full(
420d2e31
DDM
1195 int dir_fd,
1196 const char *path,
1197 int open_flags,
1198 XOpenFlags xopen_flags,
1199 mode_t mode,
1200 LockType locktype,
1201 int operation) {
1202
2646b86d
DDM
1203 _cleanup_close_ int fd = -EBADF;
1204 int r;
1205
1206 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
2646b86d
DDM
1207 assert(IN_SET(operation & ~LOCK_NB, LOCK_EX, LOCK_SH));
1208
1209 /* POSIX/UNPOSIX locks don't work on directories (errno is set to -EBADF so let's return early with
1210 * the same error here). */
0867a465 1211 if (FLAGS_SET(open_flags, O_DIRECTORY) && !IN_SET(locktype, LOCK_BSD, LOCK_NONE))
2646b86d
DDM
1212 return -EBADF;
1213
1214 for (;;) {
1215 struct stat st;
1216
e40b11be 1217 fd = xopenat_full(dir_fd, path, open_flags, xopen_flags, mode);
2646b86d
DDM
1218 if (fd < 0)
1219 return fd;
1220
1221 r = lock_generic(fd, locktype, operation);
1222 if (r < 0)
1223 return r;
1224
1225 /* If we acquired the lock, let's check if the file/directory still exists in the file
1226 * system. If not, then the previous exclusive owner removed it and then closed it. In such a
1227 * case our acquired lock is worthless, hence try again. */
1228
1229 if (fstat(fd, &st) < 0)
1230 return -errno;
1231 if (st.st_nlink > 0)
1232 break;
1233
1234 fd = safe_close(fd);
1235 }
1236
1237 return TAKE_FD(fd);
1238}
0b8e36f0
LP
1239
1240int link_fd(int fd, int newdirfd, const char *newpath) {
1241 int r;
1242
1243 assert(fd >= 0);
1244 assert(newdirfd >= 0 || newdirfd == AT_FDCWD);
1245 assert(newpath);
1246
1247 /* Try linking via /proc/self/fd/ first. */
1248 r = RET_NERRNO(linkat(AT_FDCWD, FORMAT_PROC_FD_PATH(fd), newdirfd, newpath, AT_SYMLINK_FOLLOW));
1249 if (r != -ENOENT)
1250 return r;
1251
1252 /* Fall back to symlinking via AT_EMPTY_PATH as fallback (this requires CAP_DAC_READ_SEARCH and a
1253 * more recent kernel, but does not require /proc/ mounted) */
1254 if (proc_mounted() != 0)
1255 return r;
1256
1257 return RET_NERRNO(linkat(fd, "", newdirfd, newpath, AT_EMPTY_PATH));
1258}
1f27e7b7
LP
1259
1260int linkat_replace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
1261 _cleanup_close_ int old_fd = -EBADF;
1262 int r;
1263
1264 assert(olddirfd >= 0 || olddirfd == AT_FDCWD);
1265 assert(newdirfd >= 0 || newdirfd == AT_FDCWD);
1266 assert(!isempty(newpath)); /* source path is optional, but the target path is not */
1267
1268 /* Like linkat() but replaces the target if needed. Is a NOP if source and target already share the
1269 * same inode. */
1270
1271 if (olddirfd == AT_FDCWD && isempty(oldpath)) /* Refuse operating on the cwd (which is a dir, and dirs can't be hardlinked) */
1272 return -EISDIR;
1273
1274 if (path_implies_directory(oldpath)) /* Refuse these definite directories early */
1275 return -EISDIR;
1276
1277 if (path_implies_directory(newpath))
1278 return -EISDIR;
1279
1280 /* First, try to link this directly */
1281 if (oldpath)
1282 r = RET_NERRNO(linkat(olddirfd, oldpath, newdirfd, newpath, 0));
1283 else
1284 r = link_fd(olddirfd, newdirfd, newpath);
1285 if (r >= 0)
1286 return 0;
1287 if (r != -EEXIST)
1288 return r;
1289
1290 old_fd = xopenat(olddirfd, oldpath, O_PATH|O_CLOEXEC);
1291 if (old_fd < 0)
1292 return old_fd;
1293
1294 struct stat old_st;
1295 if (fstat(old_fd, &old_st) < 0)
1296 return -errno;
1297
1298 if (S_ISDIR(old_st.st_mode)) /* Don't bother if we are operating on a directory */
1299 return -EISDIR;
1300
1301 struct stat new_st;
1302 if (fstatat(newdirfd, newpath, &new_st, AT_SYMLINK_NOFOLLOW) < 0)
1303 return -errno;
1304
1305 if (S_ISDIR(new_st.st_mode)) /* Refuse replacing directories */
1306 return -EEXIST;
1307
1308 if (stat_inode_same(&old_st, &new_st)) /* Already the same inode? Then shortcut this */
1309 return 0;
1310
1311 _cleanup_free_ char *tmp_path = NULL;
1312 r = tempfn_random(newpath, /* extra= */ NULL, &tmp_path);
1313 if (r < 0)
1314 return r;
1315
1316 r = link_fd(old_fd, newdirfd, tmp_path);
1317 if (r < 0) {
1318 if (!ERRNO_IS_PRIVILEGE(r))
1319 return r;
1320
1321 /* If that didn't work due to permissions then go via the path of the dentry */
1322 r = RET_NERRNO(linkat(olddirfd, oldpath, newdirfd, tmp_path, 0));
1323 if (r < 0)
1324 return r;
1325 }
1326
1327 r = RET_NERRNO(renameat(newdirfd, tmp_path, newdirfd, newpath));
1328 if (r < 0) {
1329 (void) unlinkat(newdirfd, tmp_path, /* flags= */ 0);
1330 return r;
1331 }
1332
1333 return 0;
1334}