chiark / gitweb /
fd-util: add new call rearrange_stdio()
[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   systemd is free software; you can redistribute it and/or modify it
8   under the terms of the GNU Lesser General Public License as published by
9   the Free Software Foundation; either version 2.1 of the License, or
10   (at your option) any later version.
11
12   systemd is distributed in the hope that it will be useful, but
13   WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   Lesser General Public License for more details.
16
17   You should have received a copy of the GNU Lesser General Public License
18   along with systemd; If not, see <http://www.gnu.org/licenses/>.
19 ***/
20
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <sys/resource.h>
24 #include <sys/socket.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27
28 #include "dirent-util.h"
29 #include "fd-util.h"
30 #include "fileio.h"
31 #include "fs-util.h"
32 #include "macro.h"
33 #include "memfd-util.h"
34 #include "missing.h"
35 #include "parse-util.h"
36 #include "path-util.h"
37 #include "process-util.h"
38 #include "socket-util.h"
39 #include "stdio-util.h"
40 #include "util.h"
41
42 int close_nointr(int fd) {
43         assert(fd >= 0);
44
45         if (close(fd) >= 0)
46                 return 0;
47
48         /*
49          * Just ignore EINTR; a retry loop is the wrong thing to do on
50          * Linux.
51          *
52          * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
53          * https://bugzilla.gnome.org/show_bug.cgi?id=682819
54          * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
55          * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
56          */
57         if (errno == EINTR)
58                 return 0;
59
60         return -errno;
61 }
62
63 int safe_close(int fd) {
64
65         /*
66          * Like close_nointr() but cannot fail. Guarantees errno is
67          * unchanged. Is a NOP with negative fds passed, and returns
68          * -1, so that it can be used in this syntax:
69          *
70          * fd = safe_close(fd);
71          */
72
73         if (fd >= 0) {
74                 PROTECT_ERRNO;
75
76                 /* The kernel might return pretty much any error code
77                  * via close(), but the fd will be closed anyway. The
78                  * only condition we want to check for here is whether
79                  * the fd was invalid at all... */
80
81                 assert_se(close_nointr(fd) != -EBADF);
82         }
83
84         return -1;
85 }
86
87 void safe_close_pair(int p[]) {
88         assert(p);
89
90         if (p[0] == p[1]) {
91                 /* Special case pairs which use the same fd in both
92                  * directions... */
93                 p[0] = p[1] = safe_close(p[0]);
94                 return;
95         }
96
97         p[0] = safe_close(p[0]);
98         p[1] = safe_close(p[1]);
99 }
100
101 void close_many(const int fds[], unsigned n_fd) {
102         unsigned i;
103
104         assert(fds || n_fd <= 0);
105
106         for (i = 0; i < n_fd; i++)
107                 safe_close(fds[i]);
108 }
109
110 int fclose_nointr(FILE *f) {
111         assert(f);
112
113         /* Same as close_nointr(), but for fclose() */
114
115         if (fclose(f) == 0)
116                 return 0;
117
118         if (errno == EINTR)
119                 return 0;
120
121         return -errno;
122 }
123
124 FILE* safe_fclose(FILE *f) {
125
126         /* Same as safe_close(), but for fclose() */
127
128         if (f) {
129                 PROTECT_ERRNO;
130
131                 assert_se(fclose_nointr(f) != EBADF);
132         }
133
134         return NULL;
135 }
136
137 #if 0 /// UNNEEDED by elogind
138 DIR* safe_closedir(DIR *d) {
139
140         if (d) {
141                 PROTECT_ERRNO;
142
143                 assert_se(closedir(d) >= 0 || errno != EBADF);
144         }
145
146         return NULL;
147 }
148 #endif // 0
149
150 int fd_nonblock(int fd, bool nonblock) {
151         int flags, nflags;
152
153         assert(fd >= 0);
154
155         flags = fcntl(fd, F_GETFL, 0);
156         if (flags < 0)
157                 return -errno;
158
159         if (nonblock)
160                 nflags = flags | O_NONBLOCK;
161         else
162                 nflags = flags & ~O_NONBLOCK;
163
164         if (nflags == flags)
165                 return 0;
166
167         if (fcntl(fd, F_SETFL, nflags) < 0)
168                 return -errno;
169
170         return 0;
171 }
172
173 int fd_cloexec(int fd, bool cloexec) {
174         int flags, nflags;
175
176         assert(fd >= 0);
177
178         flags = fcntl(fd, F_GETFD, 0);
179         if (flags < 0)
180                 return -errno;
181
182         if (cloexec)
183                 nflags = flags | FD_CLOEXEC;
184         else
185                 nflags = flags & ~FD_CLOEXEC;
186
187         if (nflags == flags)
188                 return 0;
189
190         if (fcntl(fd, F_SETFD, nflags) < 0)
191                 return -errno;
192
193         return 0;
194 }
195
196 void stdio_unset_cloexec(void) {
197         (void) fd_cloexec(STDIN_FILENO, false);
198         (void) fd_cloexec(STDOUT_FILENO, false);
199         (void) fd_cloexec(STDERR_FILENO, false);
200 }
201
202 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
203         unsigned i;
204
205         assert(n_fdset == 0 || fdset);
206
207         for (i = 0; i < n_fdset; i++)
208                 if (fdset[i] == fd)
209                         return true;
210
211         return false;
212 }
213
214 int close_all_fds(const int except[], unsigned n_except) {
215         _cleanup_closedir_ DIR *d = NULL;
216         struct dirent *de;
217         int r = 0;
218
219         assert(n_except == 0 || except);
220
221         d = opendir("/proc/self/fd");
222         if (!d) {
223                 int fd;
224                 struct rlimit rl;
225
226                 /* When /proc isn't available (for example in chroots)
227                  * the fallback is brute forcing through the fd
228                  * table */
229
230                 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
231                 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
232                         int q;
233
234                         if (fd_in_set(fd, except, n_except))
235                                 continue;
236
237                         q = close_nointr(fd);
238                         if (q < 0 && q != -EBADF && r >= 0)
239                                 r = q;
240                 }
241
242                 return r;
243         }
244
245         FOREACH_DIRENT(de, d, return -errno) {
246                 int fd = -1, q;
247
248                 if (safe_atoi(de->d_name, &fd) < 0)
249                         /* Let's better ignore this, just in case */
250                         continue;
251
252                 if (fd < 3)
253                         continue;
254
255                 if (fd == dirfd(d))
256                         continue;
257
258                 if (fd_in_set(fd, except, n_except))
259                         continue;
260
261                 q = close_nointr(fd);
262                 if (q < 0 && q != -EBADF && r >= 0) /* Valgrind has its own FD and doesn't want to have it closed */
263                         r = q;
264         }
265
266         return r;
267 }
268
269 #if 0 /// UNNEEDED by elogind
270 int same_fd(int a, int b) {
271         struct stat sta, stb;
272         pid_t pid;
273         int r, fa, fb;
274
275         assert(a >= 0);
276         assert(b >= 0);
277
278         /* Compares two file descriptors. Note that semantics are
279          * quite different depending on whether we have kcmp() or we
280          * don't. If we have kcmp() this will only return true for
281          * dup()ed file descriptors, but not otherwise. If we don't
282          * have kcmp() this will also return true for two fds of the same
283          * file, created by separate open() calls. Since we use this
284          * call mostly for filtering out duplicates in the fd store
285          * this difference hopefully doesn't matter too much. */
286
287         if (a == b)
288                 return true;
289
290         /* Try to use kcmp() if we have it. */
291         pid = getpid_cached();
292         r = kcmp(pid, pid, KCMP_FILE, a, b);
293         if (r == 0)
294                 return true;
295         if (r > 0)
296                 return false;
297         if (errno != ENOSYS)
298                 return -errno;
299
300         /* We don't have kcmp(), use fstat() instead. */
301         if (fstat(a, &sta) < 0)
302                 return -errno;
303
304         if (fstat(b, &stb) < 0)
305                 return -errno;
306
307         if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
308                 return false;
309
310         /* We consider all device fds different, since two device fds
311          * might refer to quite different device contexts even though
312          * they share the same inode and backing dev_t. */
313
314         if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
315                 return false;
316
317         if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
318                 return false;
319
320         /* The fds refer to the same inode on disk, let's also check
321          * if they have the same fd flags. This is useful to
322          * distinguish the read and write side of a pipe created with
323          * pipe(). */
324         fa = fcntl(a, F_GETFL);
325         if (fa < 0)
326                 return -errno;
327
328         fb = fcntl(b, F_GETFL);
329         if (fb < 0)
330                 return -errno;
331
332         return fa == fb;
333 }
334
335 void cmsg_close_all(struct msghdr *mh) {
336         struct cmsghdr *cmsg;
337
338         assert(mh);
339
340         CMSG_FOREACH(cmsg, mh)
341                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
342                         close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
343 }
344
345 bool fdname_is_valid(const char *s) {
346         const char *p;
347
348         /* Validates a name for $LISTEN_FDNAMES. We basically allow
349          * everything ASCII that's not a control character. Also, as
350          * special exception the ":" character is not allowed, as we
351          * use that as field separator in $LISTEN_FDNAMES.
352          *
353          * Note that the empty string is explicitly allowed
354          * here. However, we limit the length of the names to 255
355          * characters. */
356
357         if (!s)
358                 return false;
359
360         for (p = s; *p; p++) {
361                 if (*p < ' ')
362                         return false;
363                 if (*p >= 127)
364                         return false;
365                 if (*p == ':')
366                         return false;
367         }
368
369         return p - s < 256;
370 }
371
372 int fd_get_path(int fd, char **ret) {
373         char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
374         int r;
375
376         xsprintf(procfs_path, "/proc/self/fd/%i", fd);
377
378         r = readlink_malloc(procfs_path, ret);
379
380         if (r == -ENOENT) /* If the file doesn't exist the fd is invalid */
381                 return -EBADF;
382
383         return r;
384 }
385 #endif // 0
386
387 int move_fd(int from, int to, int cloexec) {
388         int r;
389
390         /* Move fd 'from' to 'to', make sure FD_CLOEXEC remains equal if requested, and release the old fd. If
391          * 'cloexec' is passed as -1, the original FD_CLOEXEC is inherited for the new fd. If it is 0, it is turned
392          * off, if it is > 0 it is turned on. */
393
394         if (from < 0)
395                 return -EBADF;
396         if (to < 0)
397                 return -EBADF;
398
399         if (from == to) {
400
401                 if (cloexec >= 0) {
402                         r = fd_cloexec(to, cloexec);
403                         if (r < 0)
404                                 return r;
405                 }
406
407                 return to;
408         }
409
410         if (cloexec < 0) {
411                 int fl;
412
413                 fl = fcntl(from, F_GETFD, 0);
414                 if (fl < 0)
415                         return -errno;
416
417                 cloexec = !!(fl & FD_CLOEXEC);
418         }
419
420         r = dup3(from, to, cloexec ? O_CLOEXEC : 0);
421         if (r < 0)
422                 return -errno;
423
424         assert(r == to);
425
426         safe_close(from);
427
428         return to;
429 }
430
431 int acquire_data_fd(const void *data, size_t size, unsigned flags) {
432
433         char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
434         _cleanup_close_pair_ int pipefds[2] = { -1, -1 };
435         char pattern[] = "/dev/shm/data-fd-XXXXXX";
436         _cleanup_close_ int fd = -1;
437         int isz = 0, r;
438         ssize_t n;
439         off_t f;
440
441         assert(data || size == 0);
442
443         /* Acquire a read-only file descriptor that when read from returns the specified data. This is much more
444          * complex than I wish it was. But here's why:
445          *
446          * a) First we try to use memfds. They are the best option, as we can seal them nicely to make them
447          *    read-only. Unfortunately they require kernel 3.17, and – at the time of writing – we still support 3.14.
448          *
449          * b) Then, we try classic pipes. They are the second best options, as we can close the writing side, retaining
450          *    a nicely read-only fd in the reading side. However, they are by default quite small, and unprivileged
451          *    clients can only bump their size to a system-wide limit, which might be quite low.
452          *
453          * c) Then, we try an O_TMPFILE file in /dev/shm (that dir is the only suitable one known to exist from
454          *    earliest boot on). To make it read-only we open the fd a second time with O_RDONLY via
455          *    /proc/self/<fd>. Unfortunately O_TMPFILE is not available on older kernels on tmpfs.
456          *
457          * d) Finally, we try creating a regular file in /dev/shm, which we then delete.
458          *
459          * It sucks a bit that depending on the situation we return very different objects here, but that's Linux I
460          * figure. */
461
462         if (size == 0 && ((flags & ACQUIRE_NO_DEV_NULL) == 0)) {
463                 /* As a special case, return /dev/null if we have been called for an empty data block */
464                 r = open("/dev/null", O_RDONLY|O_CLOEXEC|O_NOCTTY);
465                 if (r < 0)
466                         return -errno;
467
468                 return r;
469         }
470
471         if ((flags & ACQUIRE_NO_MEMFD) == 0) {
472                 fd = memfd_new("data-fd");
473                 if (fd < 0)
474                         goto try_pipe;
475
476                 n = write(fd, data, size);
477                 if (n < 0)
478                         return -errno;
479                 if ((size_t) n != size)
480                         return -EIO;
481
482                 f = lseek(fd, 0, SEEK_SET);
483                 if (f != 0)
484                         return -errno;
485
486                 r = memfd_set_sealed(fd);
487                 if (r < 0)
488                         return r;
489
490                 r = fd;
491                 fd = -1;
492
493                 return r;
494         }
495
496 try_pipe:
497         if ((flags & ACQUIRE_NO_PIPE) == 0) {
498                 if (pipe2(pipefds, O_CLOEXEC|O_NONBLOCK) < 0)
499                         return -errno;
500
501                 isz = fcntl(pipefds[1], F_GETPIPE_SZ, 0);
502                 if (isz < 0)
503                         return -errno;
504
505                 if ((size_t) isz < size) {
506                         isz = (int) size;
507                         if (isz < 0 || (size_t) isz != size)
508                                 return -E2BIG;
509
510                         /* Try to bump the pipe size */
511                         (void) fcntl(pipefds[1], F_SETPIPE_SZ, isz);
512
513                         /* See if that worked */
514                         isz = fcntl(pipefds[1], F_GETPIPE_SZ, 0);
515                         if (isz < 0)
516                                 return -errno;
517
518                         if ((size_t) isz < size)
519                                 goto try_dev_shm;
520                 }
521
522                 n = write(pipefds[1], data, size);
523                 if (n < 0)
524                         return -errno;
525                 if ((size_t) n != size)
526                         return -EIO;
527
528                 (void) fd_nonblock(pipefds[0], false);
529
530                 r = pipefds[0];
531                 pipefds[0] = -1;
532
533                 return r;
534         }
535
536 try_dev_shm:
537         if ((flags & ACQUIRE_NO_TMPFILE) == 0) {
538                 fd = open("/dev/shm", O_RDWR|O_TMPFILE|O_CLOEXEC, 0500);
539                 if (fd < 0)
540                         goto try_dev_shm_without_o_tmpfile;
541
542                 n = write(fd, data, size);
543                 if (n < 0)
544                         return -errno;
545                 if ((size_t) n != size)
546                         return -EIO;
547
548                 /* Let's reopen the thing, in order to get an O_RDONLY fd for the original O_RDWR one */
549                 xsprintf(procfs_path, "/proc/self/fd/%i", fd);
550                 r = open(procfs_path, O_RDONLY|O_CLOEXEC);
551                 if (r < 0)
552                         return -errno;
553
554                 return r;
555         }
556
557 try_dev_shm_without_o_tmpfile:
558         if ((flags & ACQUIRE_NO_REGULAR) == 0) {
559                 fd = mkostemp_safe(pattern);
560                 if (fd < 0)
561                         return fd;
562
563                 n = write(fd, data, size);
564                 if (n < 0) {
565                         r = -errno;
566                         goto unlink_and_return;
567                 }
568                 if ((size_t) n != size) {
569                         r = -EIO;
570                         goto unlink_and_return;
571                 }
572
573                 /* Let's reopen the thing, in order to get an O_RDONLY fd for the original O_RDWR one */
574                 r = open(pattern, O_RDONLY|O_CLOEXEC);
575                 if (r < 0)
576                         r = -errno;
577
578         unlink_and_return:
579                 (void) unlink(pattern);
580                 return r;
581         }
582
583         return -EOPNOTSUPP;
584 }
585
586 int fd_move_above_stdio(int fd) {
587         int flags, copy;
588         PROTECT_ERRNO;
589
590         /* Moves the specified file descriptor if possible out of the range [0…2], i.e. the range of
591          * stdin/stdout/stderr. If it can't be moved outside of this range the original file descriptor is
592          * returned. This call is supposed to be used for long-lasting file descriptors we allocate in our code that
593          * might get loaded into foreign code, and where we want ensure our fds are unlikely used accidentally as
594          * stdin/stdout/stderr of unrelated code.
595          *
596          * Note that this doesn't fix any real bugs, it just makes it less likely that our code will be affected by
597          * buggy code from others that mindlessly invokes 'fprintf(stderr, …' or similar in places where stderr has
598          * been closed before.
599          *
600          * This function is written in a "best-effort" and "least-impact" style. This means whenever we encounter an
601          * error we simply return the original file descriptor, and we do not touch errno. */
602
603         if (fd < 0 || fd > 2)
604                 return fd;
605
606         flags = fcntl(fd, F_GETFD, 0);
607         if (flags < 0)
608                 return fd;
609
610         if (flags & FD_CLOEXEC)
611                 copy = fcntl(fd, F_DUPFD_CLOEXEC, 3);
612         else
613                 copy = fcntl(fd, F_DUPFD, 3);
614         if (copy < 0)
615                 return fd;
616
617         assert(copy > 2);
618
619         (void) close(fd);
620         return copy;
621 }
622
623 int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd) {
624
625         int fd[3] = { /* Put together an array of fds we work on */
626                 original_input_fd,
627                 original_output_fd,
628                 original_error_fd
629         };
630
631         int r, i,
632                 null_fd = -1,                /* if we open /dev/null, we store the fd to it here */
633                 copy_fd[3] = { -1, -1, -1 }; /* This contains all fds we duplicate here temporarily, and hence need to close at the end */
634         bool null_readable, null_writable;
635
636         /* Sets up stdin, stdout, stderr with the three file descriptors passed in. If any of the descriptors is
637          * specified as -1 it will be connected with /dev/null instead. If any of the file descriptors is passed as
638          * itself (e.g. stdin as STDIN_FILENO) it is left unmodified, but the O_CLOEXEC bit is turned off should it be
639          * on.
640          *
641          * Note that if any of the passed file descriptors are > 2 they will be closed — both on success and on
642          * failure! Thus, callers should assume that when this function returns the input fds are invalidated.
643          *
644          * Note that when this function fails stdin/stdout/stderr might remain half set up!
645          *
646          * O_CLOEXEC is turned off for all three file descriptors (which is how it should be for
647          * stdin/stdout/stderr). */
648
649         null_readable = original_input_fd < 0;
650         null_writable = original_output_fd < 0 || original_error_fd < 0;
651
652         /* First step, open /dev/null once, if we need it */
653         if (null_readable || null_writable) {
654
655                 /* Let's open this with O_CLOEXEC first, and convert it to non-O_CLOEXEC when we move the fd to the final position. */
656                 null_fd = open("/dev/null", (null_readable && null_writable ? O_RDWR :
657                                              null_readable ? O_RDONLY : O_WRONLY) | O_CLOEXEC);
658                 if (null_fd < 0) {
659                         r = -errno;
660                         goto finish;
661                 }
662
663                 /* If this fd is in the 0…2 range, let's move it out of it */
664                 if (null_fd < 3) {
665                         int copy;
666
667                         copy = fcntl(null_fd, F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
668                         if (copy < 0) {
669                                 r = -errno;
670                                 goto finish;
671                         }
672
673                         safe_close(null_fd);
674                         null_fd = copy;
675                 }
676         }
677
678         /* Let's assemble fd[] with the fds to install in place of stdin/stdout/stderr */
679         for (i = 0; i < 3; i++) {
680
681                 if (fd[i] < 0)
682                         fd[i] = null_fd;        /* A negative parameter means: connect this one to /dev/null */
683                 else if (fd[i] != i && fd[i] < 3) {
684                         /* 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. */
685                         copy_fd[i] = fcntl(fd[i], F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
686                         if (copy_fd[i] < 0) {
687                                 r = -errno;
688                                 goto finish;
689                         }
690
691                         fd[i] = copy_fd[i];
692                 }
693         }
694
695         /* At this point we now have the fds to use in fd[], and they are all above the stdio range, so that we
696          * have freedom to move them around. If the fds already were at the right places then the specific fds are
697          * -1. Let's now move them to the right places. This is the point of no return. */
698         for (i = 0; i < 3; i++) {
699
700                 if (fd[i] == i) {
701
702                         /* fd is already in place, but let's make sure O_CLOEXEC is off */
703                         r = fd_cloexec(i, false);
704                         if (r < 0)
705                                 goto finish;
706
707                 } else {
708                         assert(fd[i] > 2);
709
710                         if (dup2(fd[i], i) < 0) { /* Turns off O_CLOEXEC on the new fd. */
711                                 r = -errno;
712                                 goto finish;
713                         }
714                 }
715         }
716
717         r = 0;
718
719 finish:
720         /* Close the original fds, but only if they were outside of the stdio range. Also, properly check for the same
721          * fd passed in multiple times. */
722         safe_close_above_stdio(original_input_fd);
723         if (original_output_fd != original_input_fd)
724                 safe_close_above_stdio(original_output_fd);
725         if (original_error_fd != original_input_fd && original_error_fd != original_output_fd)
726                 safe_close_above_stdio(original_error_fd);
727
728         /* Close the copies we moved > 2 */
729         for (i = 0; i < 3; i++)
730                 safe_close(copy_fd[i]);
731
732         /* Close our null fd, if it's > 2 */
733         safe_close_above_stdio(null_fd);
734
735         return r;
736 }