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