]> git.proxmox.com Git - systemd.git/blob - src/basic/fd-util.c
New upstream version 245.7
[systemd.git] / src / basic / fd-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <sys/resource.h>
6 #include <sys/stat.h>
7 #include <unistd.h>
8
9 #include "alloc-util.h"
10 #include "copy.h"
11 #include "dirent-util.h"
12 #include "fd-util.h"
13 #include "fileio.h"
14 #include "fs-util.h"
15 #include "io-util.h"
16 #include "macro.h"
17 #include "memfd-util.h"
18 #include "missing_fcntl.h"
19 #include "missing_syscall.h"
20 #include "parse-util.h"
21 #include "path-util.h"
22 #include "process-util.h"
23 #include "socket-util.h"
24 #include "stdio-util.h"
25 #include "util.h"
26 #include "tmpfile-util.h"
27
28 /* The maximum number of iterations in the loop to close descriptors in the fallback case
29 * when /proc/self/fd/ is inaccessible. */
30 #define MAX_FD_LOOP_LIMIT (1024*1024)
31
32 int close_nointr(int fd) {
33 assert(fd >= 0);
34
35 if (close(fd) >= 0)
36 return 0;
37
38 /*
39 * Just ignore EINTR; a retry loop is the wrong thing to do on
40 * Linux.
41 *
42 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
43 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
44 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
45 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
46 */
47 if (errno == EINTR)
48 return 0;
49
50 return -errno;
51 }
52
53 int safe_close(int fd) {
54
55 /*
56 * Like close_nointr() but cannot fail. Guarantees errno is
57 * unchanged. Is a NOP with negative fds passed, and returns
58 * -1, so that it can be used in this syntax:
59 *
60 * fd = safe_close(fd);
61 */
62
63 if (fd >= 0) {
64 PROTECT_ERRNO;
65
66 /* The kernel might return pretty much any error code
67 * via close(), but the fd will be closed anyway. The
68 * only condition we want to check for here is whether
69 * the fd was invalid at all... */
70
71 assert_se(close_nointr(fd) != -EBADF);
72 }
73
74 return -1;
75 }
76
77 void safe_close_pair(int p[static 2]) {
78 assert(p);
79
80 if (p[0] == p[1]) {
81 /* Special case pairs which use the same fd in both
82 * directions... */
83 p[0] = p[1] = safe_close(p[0]);
84 return;
85 }
86
87 p[0] = safe_close(p[0]);
88 p[1] = safe_close(p[1]);
89 }
90
91 void close_many(const int fds[], size_t n_fd) {
92 size_t i;
93
94 assert(fds || n_fd <= 0);
95
96 for (i = 0; i < n_fd; i++)
97 safe_close(fds[i]);
98 }
99
100 int fclose_nointr(FILE *f) {
101 assert(f);
102
103 /* Same as close_nointr(), but for fclose() */
104
105 errno = 0; /* Extra safety: if the FILE* object is not encapsulating an fd, it might not set errno
106 * correctly. Let's hence initialize it to zero first, so that we aren't confused by any
107 * prior errno here */
108 if (fclose(f) == 0)
109 return 0;
110
111 if (errno == EINTR)
112 return 0;
113
114 return errno_or_else(EIO);
115 }
116
117 FILE* safe_fclose(FILE *f) {
118
119 /* Same as safe_close(), but for fclose() */
120
121 if (f) {
122 PROTECT_ERRNO;
123
124 assert_se(fclose_nointr(f) != -EBADF);
125 }
126
127 return NULL;
128 }
129
130 DIR* safe_closedir(DIR *d) {
131
132 if (d) {
133 PROTECT_ERRNO;
134
135 assert_se(closedir(d) >= 0 || errno != EBADF);
136 }
137
138 return NULL;
139 }
140
141 int fd_nonblock(int fd, bool nonblock) {
142 int flags, nflags;
143
144 assert(fd >= 0);
145
146 flags = fcntl(fd, F_GETFL, 0);
147 if (flags < 0)
148 return -errno;
149
150 if (nonblock)
151 nflags = flags | O_NONBLOCK;
152 else
153 nflags = flags & ~O_NONBLOCK;
154
155 if (nflags == flags)
156 return 0;
157
158 if (fcntl(fd, F_SETFL, nflags) < 0)
159 return -errno;
160
161 return 0;
162 }
163
164 int fd_cloexec(int fd, bool cloexec) {
165 int flags, nflags;
166
167 assert(fd >= 0);
168
169 flags = fcntl(fd, F_GETFD, 0);
170 if (flags < 0)
171 return -errno;
172
173 if (cloexec)
174 nflags = flags | FD_CLOEXEC;
175 else
176 nflags = flags & ~FD_CLOEXEC;
177
178 if (nflags == flags)
179 return 0;
180
181 if (fcntl(fd, F_SETFD, nflags) < 0)
182 return -errno;
183
184 return 0;
185 }
186
187 _pure_ static bool fd_in_set(int fd, const int fdset[], size_t n_fdset) {
188 size_t i;
189
190 assert(n_fdset == 0 || fdset);
191
192 for (i = 0; i < n_fdset; i++)
193 if (fdset[i] == fd)
194 return true;
195
196 return false;
197 }
198
199 static int get_max_fd(void) {
200 struct rlimit rl;
201 rlim_t m;
202
203 /* Return the highest possible fd, based RLIMIT_NOFILE, but enforcing FD_SETSIZE-1 as lower boundary
204 * and INT_MAX as upper boundary. */
205
206 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
207 return -errno;
208
209 m = MAX(rl.rlim_cur, rl.rlim_max);
210 if (m < FD_SETSIZE) /* Let's always cover at least 1024 fds */
211 return FD_SETSIZE-1;
212
213 if (m == RLIM_INFINITY || m > INT_MAX) /* Saturate on overflow. After all fds are "int", hence can
214 * never be above INT_MAX */
215 return INT_MAX;
216
217 return (int) (m - 1);
218 }
219
220 int close_all_fds(const int except[], size_t n_except) {
221 _cleanup_closedir_ DIR *d = NULL;
222 struct dirent *de;
223 int r = 0;
224
225 assert(n_except == 0 || except);
226
227 d = opendir("/proc/self/fd");
228 if (!d) {
229 int fd, max_fd;
230
231 /* When /proc isn't available (for example in chroots) the fallback is brute forcing through
232 * the fd table */
233
234 max_fd = get_max_fd();
235 if (max_fd < 0)
236 return max_fd;
237
238 /* Refuse to do the loop over more too many elements. It's better to fail immediately than to
239 * spin the CPU for a long time. */
240 if (max_fd > MAX_FD_LOOP_LIMIT)
241 return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
242 "/proc/self/fd is inaccessible. Refusing to loop over %d potential fds.",
243 max_fd);
244
245 for (fd = 3; fd >= 0; fd = fd < max_fd ? fd + 1 : -1) {
246 int q;
247
248 if (fd_in_set(fd, except, n_except))
249 continue;
250
251 q = close_nointr(fd);
252 if (q < 0 && q != -EBADF && r >= 0)
253 r = q;
254 }
255
256 return r;
257 }
258
259 FOREACH_DIRENT(de, d, return -errno) {
260 int fd = -1, q;
261
262 if (safe_atoi(de->d_name, &fd) < 0)
263 /* Let's better ignore this, just in case */
264 continue;
265
266 if (fd < 3)
267 continue;
268
269 if (fd == dirfd(d))
270 continue;
271
272 if (fd_in_set(fd, except, n_except))
273 continue;
274
275 q = close_nointr(fd);
276 if (q < 0 && q != -EBADF && r >= 0) /* Valgrind has its own FD and doesn't want to have it closed */
277 r = q;
278 }
279
280 return r;
281 }
282
283 int same_fd(int a, int b) {
284 struct stat sta, stb;
285 pid_t pid;
286 int r, fa, fb;
287
288 assert(a >= 0);
289 assert(b >= 0);
290
291 /* Compares two file descriptors. Note that semantics are
292 * quite different depending on whether we have kcmp() or we
293 * don't. If we have kcmp() this will only return true for
294 * dup()ed file descriptors, but not otherwise. If we don't
295 * have kcmp() this will also return true for two fds of the same
296 * file, created by separate open() calls. Since we use this
297 * call mostly for filtering out duplicates in the fd store
298 * this difference hopefully doesn't matter too much. */
299
300 if (a == b)
301 return true;
302
303 /* Try to use kcmp() if we have it. */
304 pid = getpid_cached();
305 r = kcmp(pid, pid, KCMP_FILE, a, b);
306 if (r == 0)
307 return true;
308 if (r > 0)
309 return false;
310 if (!IN_SET(errno, ENOSYS, EACCES, EPERM))
311 return -errno;
312
313 /* We don't have kcmp(), use fstat() instead. */
314 if (fstat(a, &sta) < 0)
315 return -errno;
316
317 if (fstat(b, &stb) < 0)
318 return -errno;
319
320 if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
321 return false;
322
323 /* We consider all device fds different, since two device fds
324 * might refer to quite different device contexts even though
325 * they share the same inode and backing dev_t. */
326
327 if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
328 return false;
329
330 if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
331 return false;
332
333 /* The fds refer to the same inode on disk, let's also check
334 * if they have the same fd flags. This is useful to
335 * distinguish the read and write side of a pipe created with
336 * pipe(). */
337 fa = fcntl(a, F_GETFL);
338 if (fa < 0)
339 return -errno;
340
341 fb = fcntl(b, F_GETFL);
342 if (fb < 0)
343 return -errno;
344
345 return fa == fb;
346 }
347
348 void cmsg_close_all(struct msghdr *mh) {
349 struct cmsghdr *cmsg;
350
351 assert(mh);
352
353 CMSG_FOREACH(cmsg, mh)
354 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
355 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
356 }
357
358 bool fdname_is_valid(const char *s) {
359 const char *p;
360
361 /* Validates a name for $LISTEN_FDNAMES. We basically allow
362 * everything ASCII that's not a control character. Also, as
363 * special exception the ":" character is not allowed, as we
364 * use that as field separator in $LISTEN_FDNAMES.
365 *
366 * Note that the empty string is explicitly allowed
367 * here. However, we limit the length of the names to 255
368 * characters. */
369
370 if (!s)
371 return false;
372
373 for (p = s; *p; p++) {
374 if (*p < ' ')
375 return false;
376 if (*p >= 127)
377 return false;
378 if (*p == ':')
379 return false;
380 }
381
382 return p - s < 256;
383 }
384
385 int fd_get_path(int fd, char **ret) {
386 char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
387 int r;
388
389 xsprintf(procfs_path, "/proc/self/fd/%i", fd);
390 r = readlink_malloc(procfs_path, ret);
391 if (r == -ENOENT) {
392 /* ENOENT can mean two things: that the fd does not exist or that /proc is not mounted. Let's make
393 * things debuggable and distinguish the two. */
394
395 if (access("/proc/self/fd/", F_OK) < 0)
396 /* /proc is not available or not set up properly, we're most likely in some chroot
397 * environment. */
398 return errno == ENOENT ? -EOPNOTSUPP : -errno;
399
400 return -EBADF; /* The directory exists, hence it's the fd that doesn't. */
401 }
402
403 return r;
404 }
405
406 int move_fd(int from, int to, int cloexec) {
407 int r;
408
409 /* Move fd 'from' to 'to', make sure FD_CLOEXEC remains equal if requested, and release the old fd. If
410 * 'cloexec' is passed as -1, the original FD_CLOEXEC is inherited for the new fd. If it is 0, it is turned
411 * off, if it is > 0 it is turned on. */
412
413 if (from < 0)
414 return -EBADF;
415 if (to < 0)
416 return -EBADF;
417
418 if (from == to) {
419
420 if (cloexec >= 0) {
421 r = fd_cloexec(to, cloexec);
422 if (r < 0)
423 return r;
424 }
425
426 return to;
427 }
428
429 if (cloexec < 0) {
430 int fl;
431
432 fl = fcntl(from, F_GETFD, 0);
433 if (fl < 0)
434 return -errno;
435
436 cloexec = !!(fl & FD_CLOEXEC);
437 }
438
439 r = dup3(from, to, cloexec ? O_CLOEXEC : 0);
440 if (r < 0)
441 return -errno;
442
443 assert(r == to);
444
445 safe_close(from);
446
447 return to;
448 }
449
450 int acquire_data_fd(const void *data, size_t size, unsigned flags) {
451
452 _cleanup_close_pair_ int pipefds[2] = { -1, -1 };
453 char pattern[] = "/dev/shm/data-fd-XXXXXX";
454 _cleanup_close_ int fd = -1;
455 int isz = 0, r;
456 ssize_t n;
457 off_t f;
458
459 assert(data || size == 0);
460
461 /* Acquire a read-only file descriptor that when read from returns the specified data. This is much more
462 * complex than I wish it was. But here's why:
463 *
464 * a) First we try to use memfds. They are the best option, as we can seal them nicely to make them
465 * read-only. Unfortunately they require kernel 3.17, and – at the time of writing – we still support 3.14.
466 *
467 * b) Then, we try classic pipes. They are the second best options, as we can close the writing side, retaining
468 * a nicely read-only fd in the reading side. However, they are by default quite small, and unprivileged
469 * clients can only bump their size to a system-wide limit, which might be quite low.
470 *
471 * c) Then, we try an O_TMPFILE file in /dev/shm (that dir is the only suitable one known to exist from
472 * earliest boot on). To make it read-only we open the fd a second time with O_RDONLY via
473 * /proc/self/<fd>. Unfortunately O_TMPFILE is not available on older kernels on tmpfs.
474 *
475 * d) Finally, we try creating a regular file in /dev/shm, which we then delete.
476 *
477 * It sucks a bit that depending on the situation we return very different objects here, but that's Linux I
478 * figure. */
479
480 if (size == 0 && ((flags & ACQUIRE_NO_DEV_NULL) == 0)) {
481 /* As a special case, return /dev/null if we have been called for an empty data block */
482 r = open("/dev/null", O_RDONLY|O_CLOEXEC|O_NOCTTY);
483 if (r < 0)
484 return -errno;
485
486 return r;
487 }
488
489 if ((flags & ACQUIRE_NO_MEMFD) == 0) {
490 fd = memfd_new("data-fd");
491 if (fd < 0)
492 goto try_pipe;
493
494 n = write(fd, data, size);
495 if (n < 0)
496 return -errno;
497 if ((size_t) n != size)
498 return -EIO;
499
500 f = lseek(fd, 0, SEEK_SET);
501 if (f != 0)
502 return -errno;
503
504 r = memfd_set_sealed(fd);
505 if (r < 0)
506 return r;
507
508 return TAKE_FD(fd);
509 }
510
511 try_pipe:
512 if ((flags & ACQUIRE_NO_PIPE) == 0) {
513 if (pipe2(pipefds, O_CLOEXEC|O_NONBLOCK) < 0)
514 return -errno;
515
516 isz = fcntl(pipefds[1], F_GETPIPE_SZ, 0);
517 if (isz < 0)
518 return -errno;
519
520 if ((size_t) isz < size) {
521 isz = (int) size;
522 if (isz < 0 || (size_t) isz != size)
523 return -E2BIG;
524
525 /* Try to bump the pipe size */
526 (void) fcntl(pipefds[1], F_SETPIPE_SZ, isz);
527
528 /* See if that worked */
529 isz = fcntl(pipefds[1], F_GETPIPE_SZ, 0);
530 if (isz < 0)
531 return -errno;
532
533 if ((size_t) isz < size)
534 goto try_dev_shm;
535 }
536
537 n = write(pipefds[1], data, size);
538 if (n < 0)
539 return -errno;
540 if ((size_t) n != size)
541 return -EIO;
542
543 (void) fd_nonblock(pipefds[0], false);
544
545 return TAKE_FD(pipefds[0]);
546 }
547
548 try_dev_shm:
549 if ((flags & ACQUIRE_NO_TMPFILE) == 0) {
550 fd = open("/dev/shm", O_RDWR|O_TMPFILE|O_CLOEXEC, 0500);
551 if (fd < 0)
552 goto try_dev_shm_without_o_tmpfile;
553
554 n = write(fd, data, size);
555 if (n < 0)
556 return -errno;
557 if ((size_t) n != size)
558 return -EIO;
559
560 /* Let's reopen the thing, in order to get an O_RDONLY fd for the original O_RDWR one */
561 return fd_reopen(fd, O_RDONLY|O_CLOEXEC);
562 }
563
564 try_dev_shm_without_o_tmpfile:
565 if ((flags & ACQUIRE_NO_REGULAR) == 0) {
566 fd = mkostemp_safe(pattern);
567 if (fd < 0)
568 return fd;
569
570 n = write(fd, data, size);
571 if (n < 0) {
572 r = -errno;
573 goto unlink_and_return;
574 }
575 if ((size_t) n != size) {
576 r = -EIO;
577 goto unlink_and_return;
578 }
579
580 /* Let's reopen the thing, in order to get an O_RDONLY fd for the original O_RDWR one */
581 r = open(pattern, O_RDONLY|O_CLOEXEC);
582 if (r < 0)
583 r = -errno;
584
585 unlink_and_return:
586 (void) unlink(pattern);
587 return r;
588 }
589
590 return -EOPNOTSUPP;
591 }
592
593 /* When the data is smaller or equal to 64K, try to place the copy in a memfd/pipe */
594 #define DATA_FD_MEMORY_LIMIT (64U*1024U)
595
596 /* If memfd/pipe didn't work out, then let's use a file in /tmp up to a size of 1M. If it's large than that use /var/tmp instead. */
597 #define DATA_FD_TMP_LIMIT (1024U*1024U)
598
599 int fd_duplicate_data_fd(int fd) {
600
601 _cleanup_close_ int copy_fd = -1, tmp_fd = -1;
602 _cleanup_free_ void *remains = NULL;
603 size_t remains_size = 0;
604 const char *td;
605 struct stat st;
606 int r;
607
608 /* Creates a 'data' fd from the specified source fd, containing all the same data in a read-only fashion, but
609 * independent of it (i.e. the source fd can be closed and unmounted after this call succeeded). Tries to be
610 * somewhat smart about where to place the data. In the best case uses a memfd(). If memfd() are not supported
611 * uses a pipe instead. For larger data will use an unlinked file in /tmp, and for even larger data one in
612 * /var/tmp. */
613
614 if (fstat(fd, &st) < 0)
615 return -errno;
616
617 /* For now, let's only accept regular files, sockets, pipes and char devices */
618 if (S_ISDIR(st.st_mode))
619 return -EISDIR;
620 if (S_ISLNK(st.st_mode))
621 return -ELOOP;
622 if (!S_ISREG(st.st_mode) && !S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode) && !S_ISCHR(st.st_mode))
623 return -EBADFD;
624
625 /* If we have reason to believe the data is bounded in size, then let's use memfds or pipes as backing fd. Note
626 * that we use the reported regular file size only as a hint, given that there are plenty special files in
627 * /proc and /sys which report a zero file size but can be read from. */
628
629 if (!S_ISREG(st.st_mode) || st.st_size < DATA_FD_MEMORY_LIMIT) {
630
631 /* Try a memfd first */
632 copy_fd = memfd_new("data-fd");
633 if (copy_fd >= 0) {
634 off_t f;
635
636 r = copy_bytes(fd, copy_fd, DATA_FD_MEMORY_LIMIT, 0);
637 if (r < 0)
638 return r;
639
640 f = lseek(copy_fd, 0, SEEK_SET);
641 if (f != 0)
642 return -errno;
643
644 if (r == 0) {
645 /* Did it fit into the limit? If so, we are done. */
646 r = memfd_set_sealed(copy_fd);
647 if (r < 0)
648 return r;
649
650 return TAKE_FD(copy_fd);
651 }
652
653 /* Hmm, pity, this didn't fit. Let's fall back to /tmp then, see below */
654
655 } else {
656 _cleanup_(close_pairp) int pipefds[2] = { -1, -1 };
657 int isz;
658
659 /* If memfds aren't available, use a pipe. Set O_NONBLOCK so that we will get EAGAIN rather
660 * then block indefinitely when we hit the pipe size limit */
661
662 if (pipe2(pipefds, O_CLOEXEC|O_NONBLOCK) < 0)
663 return -errno;
664
665 isz = fcntl(pipefds[1], F_GETPIPE_SZ, 0);
666 if (isz < 0)
667 return -errno;
668
669 /* Try to enlarge the pipe size if necessary */
670 if ((size_t) isz < DATA_FD_MEMORY_LIMIT) {
671
672 (void) fcntl(pipefds[1], F_SETPIPE_SZ, DATA_FD_MEMORY_LIMIT);
673
674 isz = fcntl(pipefds[1], F_GETPIPE_SZ, 0);
675 if (isz < 0)
676 return -errno;
677 }
678
679 if ((size_t) isz >= DATA_FD_MEMORY_LIMIT) {
680
681 r = copy_bytes_full(fd, pipefds[1], DATA_FD_MEMORY_LIMIT, 0, &remains, &remains_size, NULL, NULL);
682 if (r < 0 && r != -EAGAIN)
683 return r; /* If we get EAGAIN it could be because of the source or because of
684 * the destination fd, we can't know, as sendfile() and friends won't
685 * tell us. Hence, treat this as reason to fall back, just to be
686 * sure. */
687 if (r == 0) {
688 /* Everything fit in, yay! */
689 (void) fd_nonblock(pipefds[0], false);
690
691 return TAKE_FD(pipefds[0]);
692 }
693
694 /* Things didn't fit in. But we read data into the pipe, let's remember that, so that
695 * when writing the new file we incorporate this first. */
696 copy_fd = TAKE_FD(pipefds[0]);
697 }
698 }
699 }
700
701 /* If we have reason to believe this will fit fine in /tmp, then use that as first fallback. */
702 if ((!S_ISREG(st.st_mode) || st.st_size < DATA_FD_TMP_LIMIT) &&
703 (DATA_FD_MEMORY_LIMIT + remains_size) < DATA_FD_TMP_LIMIT) {
704 off_t f;
705
706 tmp_fd = open_tmpfile_unlinkable(NULL /* NULL as directory means /tmp */, O_RDWR|O_CLOEXEC);
707 if (tmp_fd < 0)
708 return tmp_fd;
709
710 if (copy_fd >= 0) {
711 /* If we tried a memfd/pipe first and it ended up being too large, then copy this into the
712 * temporary file first. */
713
714 r = copy_bytes(copy_fd, tmp_fd, UINT64_MAX, 0);
715 if (r < 0)
716 return r;
717
718 assert(r == 0);
719 }
720
721 if (remains_size > 0) {
722 /* If there were remaining bytes (i.e. read into memory, but not written out yet) from the
723 * failed copy operation, let's flush them out next. */
724
725 r = loop_write(tmp_fd, remains, remains_size, false);
726 if (r < 0)
727 return r;
728 }
729
730 r = copy_bytes(fd, tmp_fd, DATA_FD_TMP_LIMIT - DATA_FD_MEMORY_LIMIT - remains_size, COPY_REFLINK);
731 if (r < 0)
732 return r;
733 if (r == 0)
734 goto finish; /* Yay, it fit in */
735
736 /* It didn't fit in. Let's not forget to use what we already used */
737 f = lseek(tmp_fd, 0, SEEK_SET);
738 if (f != 0)
739 return -errno;
740
741 safe_close(copy_fd);
742 copy_fd = TAKE_FD(tmp_fd);
743
744 remains = mfree(remains);
745 remains_size = 0;
746 }
747
748 /* As last fallback use /var/tmp */
749 r = var_tmp_dir(&td);
750 if (r < 0)
751 return r;
752
753 tmp_fd = open_tmpfile_unlinkable(td, O_RDWR|O_CLOEXEC);
754 if (tmp_fd < 0)
755 return tmp_fd;
756
757 if (copy_fd >= 0) {
758 /* If we tried a memfd/pipe first, or a file in /tmp, and it ended up being too large, than copy this
759 * into the temporary file first. */
760 r = copy_bytes(copy_fd, tmp_fd, UINT64_MAX, COPY_REFLINK);
761 if (r < 0)
762 return r;
763
764 assert(r == 0);
765 }
766
767 if (remains_size > 0) {
768 /* Then, copy in any read but not yet written bytes. */
769 r = loop_write(tmp_fd, remains, remains_size, false);
770 if (r < 0)
771 return r;
772 }
773
774 /* Copy in the rest */
775 r = copy_bytes(fd, tmp_fd, UINT64_MAX, COPY_REFLINK);
776 if (r < 0)
777 return r;
778
779 assert(r == 0);
780
781 finish:
782 /* Now convert the O_RDWR file descriptor into an O_RDONLY one (and as side effect seek to the beginning of the
783 * file again */
784
785 return fd_reopen(tmp_fd, O_RDONLY|O_CLOEXEC);
786 }
787
788 int fd_move_above_stdio(int fd) {
789 int flags, copy;
790 PROTECT_ERRNO;
791
792 /* Moves the specified file descriptor if possible out of the range [0…2], i.e. the range of
793 * stdin/stdout/stderr. If it can't be moved outside of this range the original file descriptor is
794 * returned. This call is supposed to be used for long-lasting file descriptors we allocate in our code that
795 * might get loaded into foreign code, and where we want ensure our fds are unlikely used accidentally as
796 * stdin/stdout/stderr of unrelated code.
797 *
798 * Note that this doesn't fix any real bugs, it just makes it less likely that our code will be affected by
799 * buggy code from others that mindlessly invokes 'fprintf(stderr, …' or similar in places where stderr has
800 * been closed before.
801 *
802 * This function is written in a "best-effort" and "least-impact" style. This means whenever we encounter an
803 * error we simply return the original file descriptor, and we do not touch errno. */
804
805 if (fd < 0 || fd > 2)
806 return fd;
807
808 flags = fcntl(fd, F_GETFD, 0);
809 if (flags < 0)
810 return fd;
811
812 if (flags & FD_CLOEXEC)
813 copy = fcntl(fd, F_DUPFD_CLOEXEC, 3);
814 else
815 copy = fcntl(fd, F_DUPFD, 3);
816 if (copy < 0)
817 return fd;
818
819 assert(copy > 2);
820
821 (void) close(fd);
822 return copy;
823 }
824
825 int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd) {
826
827 int fd[3] = { /* Put together an array of fds we work on */
828 original_input_fd,
829 original_output_fd,
830 original_error_fd
831 };
832
833 int r, i,
834 null_fd = -1, /* if we open /dev/null, we store the fd to it here */
835 copy_fd[3] = { -1, -1, -1 }; /* This contains all fds we duplicate here temporarily, and hence need to close at the end */
836 bool null_readable, null_writable;
837
838 /* Sets up stdin, stdout, stderr with the three file descriptors passed in. If any of the descriptors is
839 * specified as -1 it will be connected with /dev/null instead. If any of the file descriptors is passed as
840 * itself (e.g. stdin as STDIN_FILENO) it is left unmodified, but the O_CLOEXEC bit is turned off should it be
841 * on.
842 *
843 * Note that if any of the passed file descriptors are > 2 they will be closed — both on success and on
844 * failure! Thus, callers should assume that when this function returns the input fds are invalidated.
845 *
846 * Note that when this function fails stdin/stdout/stderr might remain half set up!
847 *
848 * O_CLOEXEC is turned off for all three file descriptors (which is how it should be for
849 * stdin/stdout/stderr). */
850
851 null_readable = original_input_fd < 0;
852 null_writable = original_output_fd < 0 || original_error_fd < 0;
853
854 /* First step, open /dev/null once, if we need it */
855 if (null_readable || null_writable) {
856
857 /* Let's open this with O_CLOEXEC first, and convert it to non-O_CLOEXEC when we move the fd to the final position. */
858 null_fd = open("/dev/null", (null_readable && null_writable ? O_RDWR :
859 null_readable ? O_RDONLY : O_WRONLY) | O_CLOEXEC);
860 if (null_fd < 0) {
861 r = -errno;
862 goto finish;
863 }
864
865 /* If this fd is in the 0…2 range, let's move it out of it */
866 if (null_fd < 3) {
867 int copy;
868
869 copy = fcntl(null_fd, F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
870 if (copy < 0) {
871 r = -errno;
872 goto finish;
873 }
874
875 safe_close(null_fd);
876 null_fd = copy;
877 }
878 }
879
880 /* Let's assemble fd[] with the fds to install in place of stdin/stdout/stderr */
881 for (i = 0; i < 3; i++) {
882
883 if (fd[i] < 0)
884 fd[i] = null_fd; /* A negative parameter means: connect this one to /dev/null */
885 else if (fd[i] != i && fd[i] < 3) {
886 /* 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. */
887 copy_fd[i] = fcntl(fd[i], F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
888 if (copy_fd[i] < 0) {
889 r = -errno;
890 goto finish;
891 }
892
893 fd[i] = copy_fd[i];
894 }
895 }
896
897 /* At this point we now have the fds to use in fd[], and they are all above the stdio range, so that we
898 * have freedom to move them around. If the fds already were at the right places then the specific fds are
899 * -1. Let's now move them to the right places. This is the point of no return. */
900 for (i = 0; i < 3; i++) {
901
902 if (fd[i] == i) {
903
904 /* fd is already in place, but let's make sure O_CLOEXEC is off */
905 r = fd_cloexec(i, false);
906 if (r < 0)
907 goto finish;
908
909 } else {
910 assert(fd[i] > 2);
911
912 if (dup2(fd[i], i) < 0) { /* Turns off O_CLOEXEC on the new fd. */
913 r = -errno;
914 goto finish;
915 }
916 }
917 }
918
919 r = 0;
920
921 finish:
922 /* Close the original fds, but only if they were outside of the stdio range. Also, properly check for the same
923 * fd passed in multiple times. */
924 safe_close_above_stdio(original_input_fd);
925 if (original_output_fd != original_input_fd)
926 safe_close_above_stdio(original_output_fd);
927 if (original_error_fd != original_input_fd && original_error_fd != original_output_fd)
928 safe_close_above_stdio(original_error_fd);
929
930 /* Close the copies we moved > 2 */
931 for (i = 0; i < 3; i++)
932 safe_close(copy_fd[i]);
933
934 /* Close our null fd, if it's > 2 */
935 safe_close_above_stdio(null_fd);
936
937 return r;
938 }
939
940 int fd_reopen(int fd, int flags) {
941 char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
942 int new_fd;
943
944 /* Reopens the specified fd with new flags. This is useful for convert an O_PATH fd into a regular one, or to
945 * turn O_RDWR fds into O_RDONLY fds.
946 *
947 * This doesn't work on sockets (since they cannot be open()ed, ever).
948 *
949 * This implicitly resets the file read index to 0. */
950
951 xsprintf(procfs_path, "/proc/self/fd/%i", fd);
952 new_fd = open(procfs_path, flags);
953 if (new_fd < 0)
954 return -errno;
955
956 return new_fd;
957 }
958
959 int read_nr_open(void) {
960 _cleanup_free_ char *nr_open = NULL;
961 int r;
962
963 /* Returns the kernel's current fd limit, either by reading it of /proc/sys if that works, or using the
964 * hard-coded default compiled-in value of current kernels (1M) if not. This call will never fail. */
965
966 r = read_one_line_file("/proc/sys/fs/nr_open", &nr_open);
967 if (r < 0)
968 log_debug_errno(r, "Failed to read /proc/sys/fs/nr_open, ignoring: %m");
969 else {
970 int v;
971
972 r = safe_atoi(nr_open, &v);
973 if (r < 0)
974 log_debug_errno(r, "Failed to parse /proc/sys/fs/nr_open value '%s', ignoring: %m", nr_open);
975 else
976 return v;
977 }
978
979 /* If we fail, fallback to the hard-coded kernel limit of 1024 * 1024. */
980 return 1024 * 1024;
981 }