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