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