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