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