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