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