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