]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/fd-util.c
fd-util: add new helper close_many_unset()
[thirdparty/systemd.git] / src / basic / fd-util.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
3ffd4af2 2
11c3a366
TA
3#include <errno.h>
4#include <fcntl.h>
3657d3a0 5#if WANT_LINUX_FS_H
7e93a658 6#include <linux/fs.h>
3657d3a0 7#endif
65ddc2c5
ZJS
8#include <linux/magic.h>
9#include <sys/ioctl.h>
11c3a366 10#include <sys/resource.h>
11c3a366
TA
11#include <sys/stat.h>
12#include <unistd.h>
13
4960ce43 14#include "alloc-util.h"
8fb3f009 15#include "dirent-util.h"
3ffd4af2 16#include "fd-util.h"
a548e14d 17#include "fileio.h"
4aeb20f5 18#include "fs-util.h"
4960ce43 19#include "io-util.h"
11c3a366 20#include "macro.h"
0499585f 21#include "missing_fcntl.h"
7e93a658 22#include "missing_fs.h"
f5947a5e 23#include "missing_syscall.h"
af423b4b 24#include "mountpoint-util.h"
93cc7779 25#include "parse-util.h"
11c3a366 26#include "path-util.h"
df0ff127 27#include "process-util.h"
93cc7779 28#include "socket-util.h"
b8cfa2da 29#include "sort-util.h"
f8606626 30#include "stat-util.h"
4aeb20f5 31#include "stdio-util.h"
e4de7287 32#include "tmpfile-util.h"
3ffd4af2 33
6a461d1f
ZJS
34/* The maximum number of iterations in the loop to close descriptors in the fallback case
35 * when /proc/self/fd/ is inaccessible. */
36#define MAX_FD_LOOP_LIMIT (1024*1024)
37
3ffd4af2
LP
38int close_nointr(int fd) {
39 assert(fd >= 0);
40
41 if (close(fd) >= 0)
42 return 0;
43
44 /*
45 * Just ignore EINTR; a retry loop is the wrong thing to do on
46 * Linux.
47 *
48 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
49 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
50 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
51 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
52 */
53 if (errno == EINTR)
54 return 0;
55
56 return -errno;
57}
58
59int safe_close(int fd) {
3ffd4af2 60 /*
254d1313
ZJS
61 * Like close_nointr() but cannot fail. Guarantees errno is unchanged. Is a noop for negative fds,
62 * and returns -EBADF, so that it can be used in this syntax:
3ffd4af2
LP
63 *
64 * fd = safe_close(fd);
65 */
66
67 if (fd >= 0) {
68 PROTECT_ERRNO;
69
70 /* The kernel might return pretty much any error code
71 * via close(), but the fd will be closed anyway. The
72 * only condition we want to check for here is whether
73 * the fd was invalid at all... */
74
75 assert_se(close_nointr(fd) != -EBADF);
76 }
77
254d1313 78 return -EBADF;
3ffd4af2
LP
79}
80
3042bbeb 81void safe_close_pair(int p[static 2]) {
3ffd4af2
LP
82 assert(p);
83
84 if (p[0] == p[1]) {
85 /* Special case pairs which use the same fd in both
86 * directions... */
87 p[0] = p[1] = safe_close(p[0]);
88 return;
89 }
90
91 p[0] = safe_close(p[0]);
92 p[1] = safe_close(p[1]);
93}
94
da6053d0 95void close_many(const int fds[], size_t n_fd) {
3ffd4af2
LP
96 assert(fds || n_fd <= 0);
97
fe96c0f8 98 for (size_t i = 0; i < n_fd; i++)
3ffd4af2
LP
99 safe_close(fds[i]);
100}
101
d3eb74f8
LP
102void close_many_unset(int fds[], size_t n_fd) {
103 assert(fds || n_fd <= 0);
104
105 for (size_t i = 0; i < n_fd; i++)
106 fds[i] = safe_close(fds[i]);
107}
108
3b444970
LP
109void close_many_and_free(int *fds, size_t n_fds) {
110 assert(fds || n_fds <= 0);
111
112 close_many(fds, n_fds);
113 free(fds);
114}
115
3ffd4af2
LP
116int fclose_nointr(FILE *f) {
117 assert(f);
118
119 /* Same as close_nointr(), but for fclose() */
120
75f6d5d8
LP
121 errno = 0; /* Extra safety: if the FILE* object is not encapsulating an fd, it might not set errno
122 * correctly. Let's hence initialize it to zero first, so that we aren't confused by any
123 * prior errno here */
3ffd4af2
LP
124 if (fclose(f) == 0)
125 return 0;
126
127 if (errno == EINTR)
128 return 0;
129
75f6d5d8 130 return errno_or_else(EIO);
3ffd4af2
LP
131}
132
133FILE* safe_fclose(FILE *f) {
134
135 /* Same as safe_close(), but for fclose() */
136
137 if (f) {
138 PROTECT_ERRNO;
139
6dce3bb4 140 assert_se(fclose_nointr(f) != -EBADF);
3ffd4af2
LP
141 }
142
143 return NULL;
144}
145
146DIR* safe_closedir(DIR *d) {
147
148 if (d) {
149 PROTECT_ERRNO;
150
151 assert_se(closedir(d) >= 0 || errno != EBADF);
152 }
153
154 return NULL;
155}
156
157int fd_nonblock(int fd, bool nonblock) {
158 int flags, nflags;
159
160 assert(fd >= 0);
161
162 flags = fcntl(fd, F_GETFL, 0);
163 if (flags < 0)
164 return -errno;
165
0da96503 166 nflags = UPDATE_FLAG(flags, O_NONBLOCK, nonblock);
3ffd4af2
LP
167 if (nflags == flags)
168 return 0;
169
7c248223 170 return RET_NERRNO(fcntl(fd, F_SETFL, nflags));
3ffd4af2
LP
171}
172
173int fd_cloexec(int fd, bool cloexec) {
174 int flags, nflags;
175
176 assert(fd >= 0);
177
178 flags = fcntl(fd, F_GETFD, 0);
179 if (flags < 0)
180 return -errno;
181
0da96503 182 nflags = UPDATE_FLAG(flags, FD_CLOEXEC, cloexec);
3ffd4af2
LP
183 if (nflags == flags)
184 return 0;
185
7c248223 186 return RET_NERRNO(fcntl(fd, F_SETFD, nflags));
3ffd4af2
LP
187}
188
ed18c22c
LP
189int fd_cloexec_many(const int fds[], size_t n_fds, bool cloexec) {
190 int ret = 0, r;
191
192 assert(n_fds == 0 || fds);
193
194 for (size_t i = 0; i < n_fds; i++) {
195 if (fds[i] < 0) /* Skip gracefully over already invalidated fds */
196 continue;
197
198 r = fd_cloexec(fds[i], cloexec);
199 if (r < 0 && ret >= 0) /* Continue going, but return first error */
200 ret = r;
201 else
202 ret = 1; /* report if we did anything */
203 }
204
205 return ret;
206}
207
d1e8e8b5 208static bool fd_in_set(int fd, const int fdset[], size_t n_fdset) {
3ffd4af2
LP
209 assert(n_fdset == 0 || fdset);
210
d11c14a9
LP
211 for (size_t i = 0; i < n_fdset; i++) {
212 if (fdset[i] < 0)
213 continue;
214
3ffd4af2
LP
215 if (fdset[i] == fd)
216 return true;
d11c14a9 217 }
3ffd4af2
LP
218
219 return false;
220}
221
73fc0cbc 222int get_max_fd(void) {
498e265d
LP
223 struct rlimit rl;
224 rlim_t m;
225
226 /* Return the highest possible fd, based RLIMIT_NOFILE, but enforcing FD_SETSIZE-1 as lower boundary
227 * and INT_MAX as upper boundary. */
228
229 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
230 return -errno;
231
232 m = MAX(rl.rlim_cur, rl.rlim_max);
233 if (m < FD_SETSIZE) /* Let's always cover at least 1024 fds */
234 return FD_SETSIZE-1;
235
236 if (m == RLIM_INFINITY || m > INT_MAX) /* Saturate on overflow. After all fds are "int", hence can
237 * never be above INT_MAX */
238 return INT_MAX;
239
240 return (int) (m - 1);
241}
242
5cfa0798 243static int close_all_fds_frugal(const int except[], size_t n_except) {
11966552
LP
244 int max_fd, r = 0;
245
246 assert(n_except == 0 || except);
247
248 /* This is the inner fallback core of close_all_fds(). This never calls malloc() or opendir() or so
249 * and hence is safe to be called in signal handler context. Most users should call close_all_fds(),
250 * but when we assume we are called from signal handler context, then use this simpler call
251 * instead. */
252
253 max_fd = get_max_fd();
254 if (max_fd < 0)
255 return max_fd;
256
257 /* Refuse to do the loop over more too many elements. It's better to fail immediately than to
258 * spin the CPU for a long time. */
259 if (max_fd > MAX_FD_LOOP_LIMIT)
260 return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
261 "Refusing to loop over %d potential fds.",
262 max_fd);
263
5bb1d7fb 264 for (int fd = 3; fd >= 0; fd = fd < max_fd ? fd + 1 : -EBADF) {
11966552
LP
265 int q;
266
267 if (fd_in_set(fd, except, n_except))
268 continue;
269
270 q = close_nointr(fd);
271 if (q < 0 && q != -EBADF && r >= 0)
272 r = q;
273 }
274
275 return r;
276}
277
5cfa0798 278static bool have_close_range = true; /* Assume we live in the future */
3ffd4af2 279
5cfa0798 280static int close_all_fds_special_case(const int except[], size_t n_except) {
3ffd4af2
LP
281 assert(n_except == 0 || except);
282
5cfa0798
LP
283 /* Handles a few common special cases separately, since they are common and can be optimized really
284 * nicely, since we won't need sorting for them. Returns > 0 if the special casing worked, 0
285 * otherwise. */
b8cfa2da 286
5cfa0798
LP
287 if (!have_close_range)
288 return 0;
b8cfa2da 289
d11c14a9
LP
290 if (n_except == 1 && except[0] < 0) /* Minor optimization: if we only got one fd, and it's invalid,
291 * we got none */
292 n_except = 0;
293
5cfa0798 294 switch (n_except) {
b8cfa2da 295
5cfa0798
LP
296 case 0:
297 /* Close everything. Yay! */
b8cfa2da 298
5cfa0798
LP
299 if (close_range(3, -1, 0) >= 0)
300 return 1;
f498720a 301
5cfa0798
LP
302 if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) {
303 have_close_range = false;
304 return 0;
305 }
f498720a 306
5cfa0798 307 return -errno;
f498720a 308
5cfa0798
LP
309 case 1:
310 /* Close all but exactly one, then we don't need no sorting. This is a pretty common
311 * case, hence let's handle it specially. */
f498720a 312
5cfa0798
LP
313 if ((except[0] <= 3 || close_range(3, except[0]-1, 0) >= 0) &&
314 (except[0] >= INT_MAX || close_range(MAX(3, except[0]+1), -1, 0) >= 0))
315 return 1;
f498720a 316
5cfa0798 317 if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) {
f498720a 318 have_close_range = false;
5cfa0798
LP
319 return 0;
320 }
f498720a 321
5cfa0798 322 return -errno;
c85cb3bc 323
5cfa0798
LP
324 default:
325 return 0;
326 }
327}
c85cb3bc 328
5cfa0798
LP
329int close_all_fds_without_malloc(const int except[], size_t n_except) {
330 int r;
c85cb3bc 331
5cfa0798 332 assert(n_except == 0 || except);
c85cb3bc 333
5cfa0798
LP
334 r = close_all_fds_special_case(except, n_except);
335 if (r < 0)
336 return r;
337 if (r > 0) /* special case worked! */
338 return 0;
b8cfa2da 339
5cfa0798
LP
340 return close_all_fds_frugal(except, n_except);
341}
b8cfa2da 342
5cfa0798
LP
343int close_all_fds(const int except[], size_t n_except) {
344 _cleanup_closedir_ DIR *d = NULL;
5cfa0798
LP
345 int r = 0;
346
347 assert(n_except == 0 || except);
348
349 r = close_all_fds_special_case(except, n_except);
350 if (r < 0)
351 return r;
352 if (r > 0) /* special case worked! */
353 return 0;
354
355 if (have_close_range) {
356 _cleanup_free_ int *sorted_malloc = NULL;
357 size_t n_sorted;
358 int *sorted;
359
360 /* In the best case we have close_range() to close all fds between a start and an end fd,
361 * which we can use on the "inverted" exception array, i.e. all intervals between all
362 * adjacent pairs from the sorted exception array. This changes loop complexity from O(n)
363 * where n is number of open fds to O(m⋅log(m)) where m is the number of fds to keep
364 * open. Given that we assume n ≫ m that's preferable to us. */
b8cfa2da 365
5cfa0798
LP
366 assert(n_except < SIZE_MAX);
367 n_sorted = n_except + 1;
c85cb3bc 368
5cfa0798
LP
369 if (n_sorted > 64) /* Use heap for large numbers of fds, stack otherwise */
370 sorted = sorted_malloc = new(int, n_sorted);
371 else
372 sorted = newa(int, n_sorted);
c85cb3bc 373
5cfa0798
LP
374 if (sorted) {
375 memcpy(sorted, except, n_except * sizeof(int));
c85cb3bc 376
5cfa0798
LP
377 /* Let's add fd 2 to the list of fds, to simplify the loop below, as this
378 * allows us to cover the head of the array the same way as the body */
379 sorted[n_sorted-1] = 2;
b8cfa2da 380
5cfa0798
LP
381 typesafe_qsort(sorted, n_sorted, cmp_int);
382
383 for (size_t i = 0; i < n_sorted-1; i++) {
384 int start, end;
b8cfa2da 385
5cfa0798
LP
386 start = MAX(sorted[i], 2); /* The first three fds shall always remain open */
387 end = MAX(sorted[i+1], 2);
b8cfa2da 388
5cfa0798 389 assert(end >= start);
b8cfa2da 390
5cfa0798
LP
391 if (end - start <= 1)
392 continue;
b8cfa2da 393
5cfa0798
LP
394 /* Close everything between the start and end fds (both of which shall stay open) */
395 if (close_range(start + 1, end - 1, 0) < 0) {
c85cb3bc
LP
396 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
397 return -errno;
b8cfa2da 398
c85cb3bc 399 have_close_range = false;
5cfa0798 400 break;
c85cb3bc
LP
401 }
402 }
5cfa0798
LP
403
404 if (have_close_range) {
405 /* The loop succeeded. Let's now close everything beyond the end */
406
407 if (sorted[n_sorted-1] >= INT_MAX) /* Dont let the addition below overflow */
408 return 0;
409
410 if (close_range(sorted[n_sorted-1] + 1, -1, 0) >= 0)
411 return 0;
412
413 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
414 return -errno;
415
416 have_close_range = false;
417 }
b8cfa2da 418 }
c85cb3bc
LP
419
420 /* Fallback on OOM or if close_range() is not supported */
b8cfa2da
LP
421 }
422
e7e7c07c 423 d = opendir("/proc/self/fd");
11966552 424 if (!d)
5cfa0798 425 return close_all_fds_frugal(except, n_except); /* ultimate fallback if /proc/ is not available */
3ffd4af2 426
c85cb3bc 427 FOREACH_DIRENT(de, d, return -errno) {
254d1313 428 int fd = -EBADF, q;
3ffd4af2 429
1f6639ea
LP
430 if (!IN_SET(de->d_type, DT_LNK, DT_UNKNOWN))
431 continue;
432
e652663a
DT
433 fd = parse_fd(de->d_name);
434 if (fd < 0)
c85cb3bc
LP
435 /* Let's better ignore this, just in case */
436 continue;
3ffd4af2 437
c85cb3bc
LP
438 if (fd < 3)
439 continue;
3ffd4af2 440
c85cb3bc
LP
441 if (fd == dirfd(d))
442 continue;
3ffd4af2
LP
443
444 if (fd_in_set(fd, except, n_except))
445 continue;
446
e43bc9f5 447 q = close_nointr(fd);
c85cb3bc 448 if (q < 0 && q != -EBADF && r >= 0) /* Valgrind has its own FD and doesn't want to have it closed */
e43bc9f5 449 r = q;
3ffd4af2
LP
450 }
451
452 return r;
453}
454
455int same_fd(int a, int b) {
456 struct stat sta, stb;
457 pid_t pid;
458 int r, fa, fb;
459
460 assert(a >= 0);
461 assert(b >= 0);
462
675e7fc2
LP
463 /* Compares two file descriptors. Note that semantics are quite different depending on whether we
464 * have kcmp() or we don't. If we have kcmp() this will only return true for dup()ed file
465 * descriptors, but not otherwise. If we don't have kcmp() this will also return true for two fds of
466 * the same file, created by separate open() calls. Since we use this call mostly for filtering out
467 * duplicates in the fd store this difference hopefully doesn't matter too much. */
3ffd4af2
LP
468
469 if (a == b)
470 return true;
471
472 /* Try to use kcmp() if we have it. */
df0ff127 473 pid = getpid_cached();
3ffd4af2
LP
474 r = kcmp(pid, pid, KCMP_FILE, a, b);
475 if (r == 0)
476 return true;
477 if (r > 0)
478 return false;
675e7fc2 479 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
3ffd4af2
LP
480 return -errno;
481
482 /* We don't have kcmp(), use fstat() instead. */
483 if (fstat(a, &sta) < 0)
484 return -errno;
485
486 if (fstat(b, &stb) < 0)
487 return -errno;
488
a9dac7a6 489 if (!stat_inode_same(&sta, &stb))
3ffd4af2
LP
490 return false;
491
675e7fc2
LP
492 /* We consider all device fds different, since two device fds might refer to quite different device
493 * contexts even though they share the same inode and backing dev_t. */
3ffd4af2
LP
494
495 if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
496 return false;
497
a9dac7a6
LP
498 /* The fds refer to the same inode on disk, let's also check if they have the same fd flags. This is
499 * useful to distinguish the read and write side of a pipe created with pipe(). */
3ffd4af2
LP
500 fa = fcntl(a, F_GETFL);
501 if (fa < 0)
502 return -errno;
503
504 fb = fcntl(b, F_GETFL);
505 if (fb < 0)
506 return -errno;
507
508 return fa == fb;
509}
510
511void cmsg_close_all(struct msghdr *mh) {
512 struct cmsghdr *cmsg;
513
514 assert(mh);
515
516 CMSG_FOREACH(cmsg, mh)
517 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
6759b627
TH
518 close_many(CMSG_TYPED_DATA(cmsg, int),
519 (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
3ffd4af2 520}
4fee3975
LP
521
522bool fdname_is_valid(const char *s) {
523 const char *p;
524
525 /* Validates a name for $LISTEN_FDNAMES. We basically allow
526 * everything ASCII that's not a control character. Also, as
527 * special exception the ":" character is not allowed, as we
528 * use that as field separator in $LISTEN_FDNAMES.
529 *
530 * Note that the empty string is explicitly allowed
531 * here. However, we limit the length of the names to 255
532 * characters. */
533
534 if (!s)
535 return false;
536
537 for (p = s; *p; p++) {
538 if (*p < ' ')
539 return false;
540 if (*p >= 127)
541 return false;
542 if (*p == ':')
543 return false;
544 }
545
ae3f4bae 546 return p - s <= FDNAME_MAX;
4fee3975 547}
4aeb20f5
LP
548
549int fd_get_path(int fd, char **ret) {
a0fe2a2d 550 int r;
4aeb20f5 551
46693a79
YW
552 assert(fd >= 0 || fd == AT_FDCWD);
553
554 if (fd == AT_FDCWD)
555 return safe_getcwd(ret);
556
ddb6eeaf 557 r = readlink_malloc(FORMAT_PROC_FD_PATH(fd), ret);
f267719c
LP
558 if (r == -ENOENT) {
559 /* ENOENT can mean two things: that the fd does not exist or that /proc is not mounted. Let's make
5238e957 560 * things debuggable and distinguish the two. */
4aeb20f5 561
8fe8f3aa
LP
562 if (proc_mounted() == 0)
563 return -ENOSYS; /* /proc is not available or not set up properly, we're most likely in some chroot
564 * environment. */
f267719c
LP
565 return -EBADF; /* The directory exists, hence it's the fd that doesn't. */
566 }
a0fe2a2d
LP
567
568 return r;
4aeb20f5 569}
046a82c1
LP
570
571int move_fd(int from, int to, int cloexec) {
572 int r;
573
574 /* Move fd 'from' to 'to', make sure FD_CLOEXEC remains equal if requested, and release the old fd. If
575 * 'cloexec' is passed as -1, the original FD_CLOEXEC is inherited for the new fd. If it is 0, it is turned
576 * off, if it is > 0 it is turned on. */
577
578 if (from < 0)
579 return -EBADF;
580 if (to < 0)
581 return -EBADF;
582
583 if (from == to) {
584
585 if (cloexec >= 0) {
586 r = fd_cloexec(to, cloexec);
587 if (r < 0)
588 return r;
589 }
590
591 return to;
592 }
593
594 if (cloexec < 0) {
595 int fl;
596
597 fl = fcntl(from, F_GETFD, 0);
598 if (fl < 0)
599 return -errno;
600
601 cloexec = !!(fl & FD_CLOEXEC);
602 }
603
604 r = dup3(from, to, cloexec ? O_CLOEXEC : 0);
605 if (r < 0)
606 return -errno;
607
608 assert(r == to);
609
610 safe_close(from);
611
612 return to;
613}
a548e14d 614
7fe2903c
LP
615int fd_move_above_stdio(int fd) {
616 int flags, copy;
617 PROTECT_ERRNO;
618
619 /* Moves the specified file descriptor if possible out of the range [0…2], i.e. the range of
620 * stdin/stdout/stderr. If it can't be moved outside of this range the original file descriptor is
621 * returned. This call is supposed to be used for long-lasting file descriptors we allocate in our code that
622 * might get loaded into foreign code, and where we want ensure our fds are unlikely used accidentally as
623 * stdin/stdout/stderr of unrelated code.
624 *
625 * Note that this doesn't fix any real bugs, it just makes it less likely that our code will be affected by
626 * buggy code from others that mindlessly invokes 'fprintf(stderr, …' or similar in places where stderr has
627 * been closed before.
628 *
629 * This function is written in a "best-effort" and "least-impact" style. This means whenever we encounter an
630 * error we simply return the original file descriptor, and we do not touch errno. */
631
632 if (fd < 0 || fd > 2)
633 return fd;
634
635 flags = fcntl(fd, F_GETFD, 0);
636 if (flags < 0)
637 return fd;
638
639 if (flags & FD_CLOEXEC)
640 copy = fcntl(fd, F_DUPFD_CLOEXEC, 3);
641 else
642 copy = fcntl(fd, F_DUPFD, 3);
643 if (copy < 0)
644 return fd;
645
646 assert(copy > 2);
647
648 (void) close(fd);
649 return copy;
650}
aa11e28b
LP
651
652int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd) {
351293b3
ZJS
653 int fd[3] = { original_input_fd, /* Put together an array of fds we work on */
654 original_output_fd,
655 original_error_fd },
656 null_fd = -EBADF, /* If we open /dev/null, we store the fd to it here */
657 copy_fd[3] = { -EBADF, -EBADF, -EBADF }, /* This contains all fds we duplicate here
658 * temporarily, and hence need to close at the end. */
659 r;
aa11e28b
LP
660 bool null_readable, null_writable;
661
254d1313
ZJS
662 /* Sets up stdin, stdout, stderr with the three file descriptors passed in. If any of the descriptors
663 * is specified as -EBADF it will be connected with /dev/null instead. If any of the file descriptors
664 * is passed as itself (e.g. stdin as STDIN_FILENO) it is left unmodified, but the O_CLOEXEC bit is
665 * turned off should it be on.
aa11e28b 666 *
254d1313
ZJS
667 * Note that if any of the passed file descriptors are > 2 they will be closed — both on success and
668 * on failure! Thus, callers should assume that when this function returns the input fds are
669 * invalidated.
aa11e28b
LP
670 *
671 * Note that when this function fails stdin/stdout/stderr might remain half set up!
672 *
673 * O_CLOEXEC is turned off for all three file descriptors (which is how it should be for
674 * stdin/stdout/stderr). */
675
676 null_readable = original_input_fd < 0;
677 null_writable = original_output_fd < 0 || original_error_fd < 0;
678
679 /* First step, open /dev/null once, if we need it */
680 if (null_readable || null_writable) {
681
682 /* Let's open this with O_CLOEXEC first, and convert it to non-O_CLOEXEC when we move the fd to the final position. */
683 null_fd = open("/dev/null", (null_readable && null_writable ? O_RDWR :
684 null_readable ? O_RDONLY : O_WRONLY) | O_CLOEXEC);
685 if (null_fd < 0) {
686 r = -errno;
687 goto finish;
688 }
689
690 /* If this fd is in the 0…2 range, let's move it out of it */
691 if (null_fd < 3) {
692 int copy;
693
694 copy = fcntl(null_fd, F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
695 if (copy < 0) {
696 r = -errno;
697 goto finish;
698 }
699
ee3455cf 700 close_and_replace(null_fd, copy);
aa11e28b
LP
701 }
702 }
703
704 /* Let's assemble fd[] with the fds to install in place of stdin/stdout/stderr */
351293b3 705 for (int i = 0; i < 3; i++) {
aa11e28b
LP
706
707 if (fd[i] < 0)
708 fd[i] = null_fd; /* A negative parameter means: connect this one to /dev/null */
709 else if (fd[i] != i && fd[i] < 3) {
710 /* This fd is in the 0…2 territory, but not at its intended place, move it out of there, so that we can work there. */
711 copy_fd[i] = fcntl(fd[i], F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
712 if (copy_fd[i] < 0) {
713 r = -errno;
714 goto finish;
715 }
716
717 fd[i] = copy_fd[i];
718 }
719 }
720
254d1313
ZJS
721 /* At this point we now have the fds to use in fd[], and they are all above the stdio range, so that
722 * we have freedom to move them around. If the fds already were at the right places then the specific
723 * fds are -EBADF. Let's now move them to the right places. This is the point of no return. */
351293b3 724 for (int i = 0; i < 3; i++) {
aa11e28b
LP
725
726 if (fd[i] == i) {
727
728 /* fd is already in place, but let's make sure O_CLOEXEC is off */
729 r = fd_cloexec(i, false);
730 if (r < 0)
731 goto finish;
732
733 } else {
734 assert(fd[i] > 2);
735
736 if (dup2(fd[i], i) < 0) { /* Turns off O_CLOEXEC on the new fd. */
737 r = -errno;
738 goto finish;
739 }
740 }
741 }
742
743 r = 0;
744
745finish:
746 /* Close the original fds, but only if they were outside of the stdio range. Also, properly check for the same
747 * fd passed in multiple times. */
748 safe_close_above_stdio(original_input_fd);
749 if (original_output_fd != original_input_fd)
750 safe_close_above_stdio(original_output_fd);
751 if (original_error_fd != original_input_fd && original_error_fd != original_output_fd)
752 safe_close_above_stdio(original_error_fd);
753
754 /* Close the copies we moved > 2 */
351293b3 755 for (int i = 0; i < 3; i++)
aa11e28b
LP
756 safe_close(copy_fd[i]);
757
758 /* Close our null fd, if it's > 2 */
759 safe_close_above_stdio(null_fd);
760
761 return r;
762}
f2324783
LP
763
764int fd_reopen(int fd, int flags) {
d6274e6b 765 int new_fd, r;
f2324783 766
42db4a8d
LP
767 assert(fd >= 0 || fd == AT_FDCWD);
768
f2324783
LP
769 /* Reopens the specified fd with new flags. This is useful for convert an O_PATH fd into a regular one, or to
770 * turn O_RDWR fds into O_RDONLY fds.
771 *
772 * This doesn't work on sockets (since they cannot be open()ed, ever).
773 *
42db4a8d
LP
774 * This implicitly resets the file read index to 0.
775 *
fdb583e6
LP
776 * If AT_FDCWD is specified as file descriptor gets an fd to the current cwd.
777 *
778 * If the specified file descriptor refers to a symlink via O_PATH, then this function cannot be used
779 * to follow that symlink. Because we cannot have non-O_PATH fds to symlinks reopening it without
780 * O_PATH will always result in -ELOOP. Or in other words: if you have an O_PATH fd to a symlink you
781 * can reopen it only if you pass O_PATH again. */
782
783 if (FLAGS_SET(flags, O_NOFOLLOW))
784 /* O_NOFOLLOW is not allowed in fd_reopen(), because after all this is primarily implemented
785 * via a symlink-based interface in /proc/self/fd. Let's refuse this here early. Note that
786 * the kernel would generate ELOOP here too, hence this manual check is mostly redundant –
787 * the only reason we add it here is so that the O_DIRECTORY special case (see below) behaves
788 * the same way as the non-O_DIRECTORY case. */
789 return -ELOOP;
f2324783 790
42db4a8d 791 if (FLAGS_SET(flags, O_DIRECTORY) || fd == AT_FDCWD) {
b4f73d1e
LP
792 /* If we shall reopen the fd as directory we can just go via "." and thus bypass the whole
793 * magic /proc/ directory, and make ourselves independent of that being mounted. */
42db4a8d 794 new_fd = openat(fd, ".", flags | O_DIRECTORY);
b4f73d1e
LP
795 if (new_fd < 0)
796 return -errno;
797
798 return new_fd;
799 }
800
42db4a8d
LP
801 assert(fd >= 0);
802
ddb6eeaf 803 new_fd = open(FORMAT_PROC_FD_PATH(fd), flags);
f8606626
LP
804 if (new_fd < 0) {
805 if (errno != ENOENT)
806 return -errno;
807
d6274e6b
LP
808 r = proc_mounted();
809 if (r == 0)
f8606626
LP
810 return -ENOSYS; /* if we have no /proc/, the concept is not implementable */
811
d6274e6b
LP
812 return r > 0 ? -EBADF : -ENOENT; /* If /proc/ is definitely around then this means the fd is
813 * not valid, otherwise let's propagate the original
814 * error */
f8606626 815 }
f2324783
LP
816
817 return new_fd;
818}
9264cc39 819
5f5865f0
LP
820int fd_reopen_condition(
821 int fd,
822 int flags,
823 int mask,
824 int *ret_new_fd) {
825
826 int r, new_fd;
827
828 assert(fd >= 0);
829
830 /* Invokes fd_reopen(fd, flags), but only if the existing F_GETFL flags don't match the specified
831 * flags (masked by the specified mask). This is useful for converting O_PATH fds into real fds if
832 * needed, but only then. */
833
834 r = fcntl(fd, F_GETFL);
835 if (r < 0)
836 return -errno;
837
838 if ((r & mask) == (flags & mask)) {
254d1313 839 *ret_new_fd = -EBADF;
5f5865f0
LP
840 return fd;
841 }
842
843 new_fd = fd_reopen(fd, flags);
844 if (new_fd < 0)
845 return new_fd;
846
847 *ret_new_fd = new_fd;
848 return new_fd;
849}
850
ea61e2e9
YW
851int fd_is_opath(int fd) {
852 int r;
853
854 assert(fd >= 0);
855
856 r = fcntl(fd, F_GETFL);
857 if (r < 0)
858 return -errno;
859
860 return FLAGS_SET(r, O_PATH);
861}
862
9264cc39
LP
863int read_nr_open(void) {
864 _cleanup_free_ char *nr_open = NULL;
865 int r;
866
867 /* Returns the kernel's current fd limit, either by reading it of /proc/sys if that works, or using the
868 * hard-coded default compiled-in value of current kernels (1M) if not. This call will never fail. */
869
870 r = read_one_line_file("/proc/sys/fs/nr_open", &nr_open);
871 if (r < 0)
872 log_debug_errno(r, "Failed to read /proc/sys/fs/nr_open, ignoring: %m");
873 else {
874 int v;
875
876 r = safe_atoi(nr_open, &v);
877 if (r < 0)
878 log_debug_errno(r, "Failed to parse /proc/sys/fs/nr_open value '%s', ignoring: %m", nr_open);
879 else
880 return v;
881 }
882
2aed63f4 883 /* If we fail, fall back to the hard-coded kernel limit of 1024 * 1024. */
9264cc39
LP
884 return 1024 * 1024;
885}
65ddc2c5 886
7e93a658
YW
887int fd_get_diskseq(int fd, uint64_t *ret) {
888 uint64_t diskseq;
889
890 assert(fd >= 0);
891 assert(ret);
892
893 if (ioctl(fd, BLKGETDISKSEQ, &diskseq) < 0) {
894 /* Note that the kernel is weird: non-existing ioctls currently return EINVAL
895 * rather than ENOTTY on loopback block devices. They should fix that in the kernel,
896 * but in the meantime we accept both here. */
897 if (!ERRNO_IS_NOT_SUPPORTED(errno) && errno != EINVAL)
898 return -errno;
899
900 return -EOPNOTSUPP;
901 }
902
903 *ret = diskseq;
904
905 return 0;
906}
af423b4b 907
8a65b0b2 908int path_is_root_at(int dir_fd, const char *path) {
af423b4b
DDM
909 STRUCT_NEW_STATX_DEFINE(st);
910 STRUCT_NEW_STATX_DEFINE(pst);
8a65b0b2 911 _cleanup_close_ int fd = -EBADF;
af423b4b
DDM
912 int r;
913
8a65b0b2
DDM
914 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
915
916 if (!isempty(path)) {
549a9a67 917 fd = openat(dir_fd, path, O_PATH|O_DIRECTORY|O_CLOEXEC);
8a65b0b2 918 if (fd < 0)
549a9a67 919 return errno == ENOTDIR ? false : -errno;
8a65b0b2
DDM
920
921 dir_fd = fd;
922 }
af423b4b
DDM
923
924 r = statx_fallback(dir_fd, ".", 0, STATX_TYPE|STATX_INO|STATX_MNT_ID, &st.sx);
925 if (r == -ENOTDIR)
926 return false;
927 if (r < 0)
928 return r;
929
b4cb4c5c
YW
930 r = statx_fallback(dir_fd, "..", 0, STATX_TYPE|STATX_INO|STATX_MNT_ID, &pst.sx);
931 if (r < 0)
932 return r;
933
934 /* First, compare inode. If these are different, the fd does not point to the root directory "/". */
935 if (!statx_inode_same(&st.sx, &pst.sx))
936 return false;
937
8d3c49b1
YW
938 /* Even if the parent directory has the same inode, the fd may not point to the root directory "/",
939 * and we also need to check that the mount ids are the same. Otherwise, a construct like the
940 * following could be used to trick us:
941 *
942 * $ mkdir /tmp/x /tmp/x/y
943 * $ mount --bind /tmp/x /tmp/x/y
944 *
945 * Note, statx() does not provide the mount ID and path_get_mnt_id_at() does not work when an old
bd96111d
YW
946 * kernel is used. In that case, let's assume that we do not have such spurious mount points in an
947 * early boot stage, and silently skip the following check. */
8d3c49b1 948
af423b4b
DDM
949 if (!FLAGS_SET(st.nsx.stx_mask, STATX_MNT_ID)) {
950 int mntid;
951
68a4fc8b 952 r = path_get_mnt_id_at_fallback(dir_fd, "", &mntid);
bb44fd07
ZJS
953 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
954 return true; /* skip the mount ID check */
955 if (r < 0)
af423b4b
DDM
956 return r;
957 assert(mntid >= 0);
958
959 st.nsx.stx_mnt_id = mntid;
960 st.nsx.stx_mask |= STATX_MNT_ID;
961 }
962
af423b4b
DDM
963 if (!FLAGS_SET(pst.nsx.stx_mask, STATX_MNT_ID)) {
964 int mntid;
965
68a4fc8b 966 r = path_get_mnt_id_at_fallback(dir_fd, "..", &mntid);
bb44fd07
ZJS
967 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
968 return true; /* skip the mount ID check */
969 if (r < 0)
af423b4b
DDM
970 return r;
971 assert(mntid >= 0);
972
973 pst.nsx.stx_mnt_id = mntid;
974 pst.nsx.stx_mask |= STATX_MNT_ID;
975 }
976
b4cb4c5c 977 return statx_mount_same(&st.nsx, &pst.nsx);
af423b4b 978}
b2b84f4b
LP
979
980const char *accmode_to_string(int flags) {
981 switch (flags & O_ACCMODE) {
982 case O_RDONLY:
983 return "ro";
984 case O_WRONLY:
985 return "wo";
986 case O_RDWR:
987 return "rw";
988 default:
989 return NULL;
990 }
991}