1 /* SPDX-License-Identifier: LGPL-2.1+ */
5 #include <sys/resource.h>
6 #include <sys/socket.h>
10 #include "alloc-util.h"
12 #include "dirent-util.h"
18 #include "memfd-util.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"
27 int close_nointr(int fd
) {
34 * Just ignore EINTR; a retry loop is the wrong thing to do on
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
48 int safe_close(int fd
) {
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:
55 * fd = safe_close(fd);
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... */
66 assert_se(close_nointr(fd
) != -EBADF
);
72 void safe_close_pair(int p
[]) {
76 /* Special case pairs which use the same fd in both
78 p
[0] = p
[1] = safe_close(p
[0]);
82 p
[0] = safe_close(p
[0]);
83 p
[1] = safe_close(p
[1]);
86 void close_many(const int fds
[], size_t n_fd
) {
89 assert(fds
|| n_fd
<= 0);
91 for (i
= 0; i
< n_fd
; i
++)
95 int fclose_nointr(FILE *f
) {
98 /* Same as close_nointr(), but for fclose() */
109 FILE* safe_fclose(FILE *f
) {
111 /* Same as safe_close(), but for fclose() */
116 assert_se(fclose_nointr(f
) != EBADF
);
122 DIR* safe_closedir(DIR *d
) {
127 assert_se(closedir(d
) >= 0 || errno
!= EBADF
);
133 int fd_nonblock(int fd
, bool nonblock
) {
138 flags
= fcntl(fd
, F_GETFL
, 0);
143 nflags
= flags
| O_NONBLOCK
;
145 nflags
= flags
& ~O_NONBLOCK
;
150 if (fcntl(fd
, F_SETFL
, nflags
) < 0)
156 int fd_cloexec(int fd
, bool cloexec
) {
161 flags
= fcntl(fd
, F_GETFD
, 0);
166 nflags
= flags
| FD_CLOEXEC
;
168 nflags
= flags
& ~FD_CLOEXEC
;
173 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
179 _pure_
static bool fd_in_set(int fd
, const int fdset
[], size_t n_fdset
) {
182 assert(n_fdset
== 0 || fdset
);
184 for (i
= 0; i
< n_fdset
; i
++)
191 int close_all_fds(const int except
[], size_t n_except
) {
192 _cleanup_closedir_
DIR *d
= NULL
;
196 assert(n_except
== 0 || except
);
198 d
= opendir("/proc/self/fd");
203 /* When /proc isn't available (for example in chroots) the fallback is brute forcing through the fd
206 assert_se(getrlimit(RLIMIT_NOFILE
, &rl
) >= 0);
208 if (rl
.rlim_max
== 0)
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);
215 for (fd
= 3; fd
>= 0; fd
= fd
< max_fd
? fd
+ 1 : -1) {
218 if (fd_in_set(fd
, except
, n_except
))
221 q
= close_nointr(fd
);
222 if (q
< 0 && q
!= -EBADF
&& r
>= 0)
229 FOREACH_DIRENT(de
, d
, return -errno
) {
232 if (safe_atoi(de
->d_name
, &fd
) < 0)
233 /* Let's better ignore this, just in case */
242 if (fd_in_set(fd
, except
, n_except
))
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 */
253 int same_fd(int a
, int b
) {
254 struct stat sta
, stb
;
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. */
273 /* Try to use kcmp() if we have it. */
274 pid
= getpid_cached();
275 r
= kcmp(pid
, pid
, KCMP_FILE
, a
, b
);
283 /* We don't have kcmp(), use fstat() instead. */
284 if (fstat(a
, &sta
) < 0)
287 if (fstat(b
, &stb
) < 0)
290 if ((sta
.st_mode
& S_IFMT
) != (stb
.st_mode
& S_IFMT
))
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. */
297 if (S_ISCHR(sta
.st_mode
) || S_ISBLK(sta
.st_mode
))
300 if (sta
.st_dev
!= stb
.st_dev
|| sta
.st_ino
!= stb
.st_ino
)
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
307 fa
= fcntl(a
, F_GETFL
);
311 fb
= fcntl(b
, F_GETFL
);
318 void cmsg_close_all(struct msghdr
*mh
) {
319 struct cmsghdr
*cmsg
;
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));
328 bool fdname_is_valid(const char *s
) {
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.
336 * Note that the empty string is explicitly allowed
337 * here. However, we limit the length of the names to 255
343 for (p
= s
; *p
; p
++) {
355 int fd_get_path(int fd
, char **ret
) {
356 _cleanup_close_
int dir
= -1;
357 char fdname
[DECIMAL_STR_MAX(int)];
360 dir
= open("/proc/self/fd/", O_CLOEXEC
| O_DIRECTORY
| O_PATH
);
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
;
366 xsprintf(fdname
, "%i", fd
);
368 r
= readlinkat_malloc(dir
, fdname
, ret
);
370 /* If the file doesn't exist the fd is invalid */
376 int move_fd(int from
, int to
, int cloexec
) {
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. */
391 r
= fd_cloexec(to
, cloexec
);
402 fl
= fcntl(from
, F_GETFD
, 0);
406 cloexec
= !!(fl
& FD_CLOEXEC
);
409 r
= dup3(from
, to
, cloexec
? O_CLOEXEC
: 0);
420 int acquire_data_fd(const void *data
, size_t size
, unsigned flags
) {
422 _cleanup_close_pair_
int pipefds
[2] = { -1, -1 };
423 char pattern
[] = "/dev/shm/data-fd-XXXXXX";
424 _cleanup_close_
int fd
= -1;
429 assert(data
|| size
== 0);
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:
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.
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.
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.
445 * d) Finally, we try creating a regular file in /dev/shm, which we then delete.
447 * It sucks a bit that depending on the situation we return very different objects here, but that's Linux I
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
);
459 if ((flags
& ACQUIRE_NO_MEMFD
) == 0) {
460 fd
= memfd_new("data-fd");
464 n
= write(fd
, data
, size
);
467 if ((size_t) n
!= size
)
470 f
= lseek(fd
, 0, SEEK_SET
);
474 r
= memfd_set_sealed(fd
);
482 if ((flags
& ACQUIRE_NO_PIPE
) == 0) {
483 if (pipe2(pipefds
, O_CLOEXEC
|O_NONBLOCK
) < 0)
486 isz
= fcntl(pipefds
[1], F_GETPIPE_SZ
, 0);
490 if ((size_t) isz
< size
) {
492 if (isz
< 0 || (size_t) isz
!= size
)
495 /* Try to bump the pipe size */
496 (void) fcntl(pipefds
[1], F_SETPIPE_SZ
, isz
);
498 /* See if that worked */
499 isz
= fcntl(pipefds
[1], F_GETPIPE_SZ
, 0);
503 if ((size_t) isz
< size
)
507 n
= write(pipefds
[1], data
, size
);
510 if ((size_t) n
!= size
)
513 (void) fd_nonblock(pipefds
[0], false);
515 return TAKE_FD(pipefds
[0]);
519 if ((flags
& ACQUIRE_NO_TMPFILE
) == 0) {
520 fd
= open("/dev/shm", O_RDWR
|O_TMPFILE
|O_CLOEXEC
, 0500);
522 goto try_dev_shm_without_o_tmpfile
;
524 n
= write(fd
, data
, size
);
527 if ((size_t) n
!= size
)
530 /* Let's reopen the thing, in order to get an O_RDONLY fd for the original O_RDWR one */
531 return fd_reopen(fd
, O_RDONLY
|O_CLOEXEC
);
534 try_dev_shm_without_o_tmpfile
:
535 if ((flags
& ACQUIRE_NO_REGULAR
) == 0) {
536 fd
= mkostemp_safe(pattern
);
540 n
= write(fd
, data
, size
);
543 goto unlink_and_return
;
545 if ((size_t) n
!= size
) {
547 goto unlink_and_return
;
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
);
556 (void) unlink(pattern
);
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)
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)
569 int fd_duplicate_data_fd(int fd
) {
571 _cleanup_close_
int copy_fd
= -1, tmp_fd
= -1;
572 _cleanup_free_
void *remains
= NULL
;
573 size_t remains_size
= 0;
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
584 if (fstat(fd
, &st
) < 0)
587 /* For now, let's only accept regular files, sockets, pipes and char devices */
588 if (S_ISDIR(st
.st_mode
))
590 if (S_ISLNK(st
.st_mode
))
592 if (!S_ISREG(st
.st_mode
) && !S_ISSOCK(st
.st_mode
) && !S_ISFIFO(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
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. */
599 if (!S_ISREG(st
.st_mode
) || st
.st_size
< DATA_FD_MEMORY_LIMIT
) {
601 /* Try a memfd first */
602 copy_fd
= memfd_new("data-fd");
606 r
= copy_bytes(fd
, copy_fd
, DATA_FD_MEMORY_LIMIT
, 0);
610 f
= lseek(copy_fd
, 0, SEEK_SET
);
615 /* Did it fit into the limit? If so, we are done. */
616 r
= memfd_set_sealed(copy_fd
);
620 return TAKE_FD(copy_fd
);
623 /* Hmm, pity, this didn't fit. Let's fall back to /tmp then, see below */
626 _cleanup_(close_pairp
) int pipefds
[2] = { -1, -1 };
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 */
632 if (pipe2(pipefds
, O_CLOEXEC
|O_NONBLOCK
) < 0)
635 isz
= fcntl(pipefds
[1], F_GETPIPE_SZ
, 0);
639 /* Try to enlarge the pipe size if necessary */
640 if ((size_t) isz
< DATA_FD_MEMORY_LIMIT
) {
642 (void) fcntl(pipefds
[1], F_SETPIPE_SZ
, DATA_FD_MEMORY_LIMIT
);
644 isz
= fcntl(pipefds
[1], F_GETPIPE_SZ
, 0);
649 if ((size_t) isz
>= DATA_FD_MEMORY_LIMIT
) {
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
658 /* Everything fit in, yay! */
659 (void) fd_nonblock(pipefds
[0], false);
661 return TAKE_FD(pipefds
[0]);
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]);
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
) {
676 tmp_fd
= open_tmpfile_unlinkable(NULL
/* NULL as directory means /tmp */, O_RDWR
|O_CLOEXEC
);
681 /* If we tried a memfd/pipe first and it ended up being too large, then copy this into the
682 * temporary file first. */
684 r
= copy_bytes(copy_fd
, tmp_fd
, UINT64_MAX
, 0);
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. */
695 r
= loop_write(tmp_fd
, remains
, remains_size
, false);
700 r
= copy_bytes(fd
, tmp_fd
, DATA_FD_TMP_LIMIT
- DATA_FD_MEMORY_LIMIT
- remains_size
, COPY_REFLINK
);
704 goto finish
; /* Yay, it fit in */
706 /* It didn't fit in. Let's not forget to use what we already used */
707 f
= lseek(tmp_fd
, 0, SEEK_SET
);
712 copy_fd
= TAKE_FD(tmp_fd
);
714 remains
= mfree(remains
);
718 /* As last fallback use /var/tmp */
719 r
= var_tmp_dir(&td
);
723 tmp_fd
= open_tmpfile_unlinkable(td
, O_RDWR
|O_CLOEXEC
);
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
);
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);
744 /* Copy in the rest */
745 r
= copy_bytes(fd
, tmp_fd
, UINT64_MAX
, COPY_REFLINK
);
752 /* Now convert the O_RDWR file descriptor into an O_RDONLY one (and as side effect seek to the beginning of the
755 return fd_reopen(tmp_fd
, O_RDONLY
|O_CLOEXEC
);
758 int fd_move_above_stdio(int fd
) {
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.
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.
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. */
775 if (fd
< 0 || fd
> 2)
778 flags
= fcntl(fd
, F_GETFD
, 0);
782 if (flags
& FD_CLOEXEC
)
783 copy
= fcntl(fd
, F_DUPFD_CLOEXEC
, 3);
785 copy
= fcntl(fd
, F_DUPFD
, 3);
795 int rearrange_stdio(int original_input_fd
, int original_output_fd
, int original_error_fd
) {
797 int fd
[3] = { /* Put together an array of fds we work on */
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
;
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
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.
816 * Note that when this function fails stdin/stdout/stderr might remain half set up!
818 * O_CLOEXEC is turned off for all three file descriptors (which is how it should be for
819 * stdin/stdout/stderr). */
821 null_readable
= original_input_fd
< 0;
822 null_writable
= original_output_fd
< 0 || original_error_fd
< 0;
824 /* First step, open /dev/null once, if we need it */
825 if (null_readable
|| null_writable
) {
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
);
835 /* If this fd is in the 0…2 range, let's move it out of it */
839 copy
= fcntl(null_fd
, F_DUPFD_CLOEXEC
, 3); /* Duplicate this with O_CLOEXEC set */
850 /* Let's assemble fd[] with the fds to install in place of stdin/stdout/stderr */
851 for (i
= 0; i
< 3; i
++) {
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) {
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
++) {
874 /* fd is already in place, but let's make sure O_CLOEXEC is off */
875 r
= fd_cloexec(i
, false);
882 if (dup2(fd
[i
], i
) < 0) { /* Turns off O_CLOEXEC on the new fd. */
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
);
900 /* Close the copies we moved > 2 */
901 for (i
= 0; i
< 3; i
++)
902 safe_close(copy_fd
[i
]);
904 /* Close our null fd, if it's > 2 */
905 safe_close_above_stdio(null_fd
);
910 int fd_reopen(int fd
, int flags
) {
911 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
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.
917 * This doesn't work on sockets (since they cannot be open()ed, ever).
919 * This implicitly resets the file read index to 0. */
921 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
922 new_fd
= open(procfs_path
, flags
);
929 int read_nr_open(void) {
930 _cleanup_free_
char *nr_open
= NULL
;
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. */
936 r
= read_one_line_file("/proc/sys/fs/nr_open", &nr_open
);
938 log_debug_errno(r
, "Failed to read /proc/sys/fs/nr_open, ignoring: %m");
942 r
= safe_atoi(nr_open
, &v
);
944 log_debug_errno(r
, "Failed to parse /proc/sys/fs/nr_open value '%s', ignoring: %m", nr_open
);
949 /* If we fail, fallback to the hard-coded kernel limit of 1024 * 1024. */