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