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