chiark / gitweb /
Prep v238: Uncomment now needed headers and unmask now needed functions in src/basic...
[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 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
197         unsigned i;
198
199         assert(n_fdset == 0 || fdset);
200
201         for (i = 0; i < n_fdset; i++)
202                 if (fdset[i] == fd)
203                         return true;
204
205         return false;
206 }
207
208 int close_all_fds(const int except[], unsigned n_except) {
209         _cleanup_closedir_ DIR *d = NULL;
210         struct dirent *de;
211         int r = 0;
212
213         assert(n_except == 0 || except);
214
215         d = opendir("/proc/self/fd");
216         if (!d) {
217                 int fd;
218                 struct rlimit rl;
219
220                 /* When /proc isn't available (for example in chroots)
221                  * the fallback is brute forcing through the fd
222                  * table */
223
224                 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
225                 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
226                         int q;
227
228                         if (fd_in_set(fd, except, n_except))
229                                 continue;
230
231                         q = close_nointr(fd);
232                         if (q < 0 && q != -EBADF && r >= 0)
233                                 r = q;
234                 }
235
236                 return r;
237         }
238
239         FOREACH_DIRENT(de, d, return -errno) {
240                 int fd = -1, q;
241
242                 if (safe_atoi(de->d_name, &fd) < 0)
243                         /* Let's better ignore this, just in case */
244                         continue;
245
246                 if (fd < 3)
247                         continue;
248
249                 if (fd == dirfd(d))
250                         continue;
251
252                 if (fd_in_set(fd, except, n_except))
253                         continue;
254
255                 q = close_nointr(fd);
256                 if (q < 0 && q != -EBADF && r >= 0) /* Valgrind has its own FD and doesn't want to have it closed */
257                         r = q;
258         }
259
260         return r;
261 }
262
263 #if 0 /// UNNEEDED by elogind
264 int same_fd(int a, int b) {
265         struct stat sta, stb;
266         pid_t pid;
267         int r, fa, fb;
268
269         assert(a >= 0);
270         assert(b >= 0);
271
272         /* Compares two file descriptors. Note that semantics are
273          * quite different depending on whether we have kcmp() or we
274          * don't. If we have kcmp() this will only return true for
275          * dup()ed file descriptors, but not otherwise. If we don't
276          * have kcmp() this will also return true for two fds of the same
277          * file, created by separate open() calls. Since we use this
278          * call mostly for filtering out duplicates in the fd store
279          * this difference hopefully doesn't matter too much. */
280
281         if (a == b)
282                 return true;
283
284         /* Try to use kcmp() if we have it. */
285         pid = getpid_cached();
286         r = kcmp(pid, pid, KCMP_FILE, a, b);
287         if (r == 0)
288                 return true;
289         if (r > 0)
290                 return false;
291         if (errno != ENOSYS)
292                 return -errno;
293
294         /* We don't have kcmp(), use fstat() instead. */
295         if (fstat(a, &sta) < 0)
296                 return -errno;
297
298         if (fstat(b, &stb) < 0)
299                 return -errno;
300
301         if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
302                 return false;
303
304         /* We consider all device fds different, since two device fds
305          * might refer to quite different device contexts even though
306          * they share the same inode and backing dev_t. */
307
308         if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
309                 return false;
310
311         if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
312                 return false;
313
314         /* The fds refer to the same inode on disk, let's also check
315          * if they have the same fd flags. This is useful to
316          * distinguish the read and write side of a pipe created with
317          * pipe(). */
318         fa = fcntl(a, F_GETFL);
319         if (fa < 0)
320                 return -errno;
321
322         fb = fcntl(b, F_GETFL);
323         if (fb < 0)
324                 return -errno;
325
326         return fa == fb;
327 }
328
329 void cmsg_close_all(struct msghdr *mh) {
330         struct cmsghdr *cmsg;
331
332         assert(mh);
333
334         CMSG_FOREACH(cmsg, mh)
335                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
336                         close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
337 }
338
339 bool fdname_is_valid(const char *s) {
340         const char *p;
341
342         /* Validates a name for $LISTEN_FDNAMES. We basically allow
343          * everything ASCII that's not a control character. Also, as
344          * special exception the ":" character is not allowed, as we
345          * use that as field separator in $LISTEN_FDNAMES.
346          *
347          * Note that the empty string is explicitly allowed
348          * here. However, we limit the length of the names to 255
349          * characters. */
350
351         if (!s)
352                 return false;
353
354         for (p = s; *p; p++) {
355                 if (*p < ' ')
356                         return false;
357                 if (*p >= 127)
358                         return false;
359                 if (*p == ':')
360                         return false;
361         }
362
363         return p - s < 256;
364 }
365 #endif // 0
366
367 int fd_get_path(int fd, char **ret) {
368         char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
369         int r;
370
371         xsprintf(procfs_path, "/proc/self/fd/%i", fd);
372
373         r = readlink_malloc(procfs_path, ret);
374
375         if (r == -ENOENT) /* If the file doesn't exist the fd is invalid */
376                 return -EBADF;
377
378         return r;
379 }
380
381 int move_fd(int from, int to, int cloexec) {
382         int r;
383
384         /* Move fd 'from' to 'to', make sure FD_CLOEXEC remains equal if requested, and release the old fd. If
385          * 'cloexec' is passed as -1, the original FD_CLOEXEC is inherited for the new fd. If it is 0, it is turned
386          * off, if it is > 0 it is turned on. */
387
388         if (from < 0)
389                 return -EBADF;
390         if (to < 0)
391                 return -EBADF;
392
393         if (from == to) {
394
395                 if (cloexec >= 0) {
396                         r = fd_cloexec(to, cloexec);
397                         if (r < 0)
398                                 return r;
399                 }
400
401                 return to;
402         }
403
404         if (cloexec < 0) {
405                 int fl;
406
407                 fl = fcntl(from, F_GETFD, 0);
408                 if (fl < 0)
409                         return -errno;
410
411                 cloexec = !!(fl & FD_CLOEXEC);
412         }
413
414         r = dup3(from, to, cloexec ? O_CLOEXEC : 0);
415         if (r < 0)
416                 return -errno;
417
418         assert(r == to);
419
420         safe_close(from);
421
422         return to;
423 }
424
425 int acquire_data_fd(const void *data, size_t size, unsigned flags) {
426
427         char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
428         _cleanup_close_pair_ int pipefds[2] = { -1, -1 };
429         char pattern[] = "/dev/shm/data-fd-XXXXXX";
430         _cleanup_close_ int fd = -1;
431         int isz = 0, r;
432         ssize_t n;
433         off_t f;
434
435         assert(data || size == 0);
436
437         /* Acquire a read-only file descriptor that when read from returns the specified data. This is much more
438          * complex than I wish it was. But here's why:
439          *
440          * a) First we try to use memfds. They are the best option, as we can seal them nicely to make them
441          *    read-only. Unfortunately they require kernel 3.17, and – at the time of writing – we still support 3.14.
442          *
443          * b) Then, we try classic pipes. They are the second best options, as we can close the writing side, retaining
444          *    a nicely read-only fd in the reading side. However, they are by default quite small, and unprivileged
445          *    clients can only bump their size to a system-wide limit, which might be quite low.
446          *
447          * c) Then, we try an O_TMPFILE file in /dev/shm (that dir is the only suitable one known to exist from
448          *    earliest boot on). To make it read-only we open the fd a second time with O_RDONLY via
449          *    /proc/self/<fd>. Unfortunately O_TMPFILE is not available on older kernels on tmpfs.
450          *
451          * d) Finally, we try creating a regular file in /dev/shm, which we then delete.
452          *
453          * It sucks a bit that depending on the situation we return very different objects here, but that's Linux I
454          * figure. */
455
456         if (size == 0 && ((flags & ACQUIRE_NO_DEV_NULL) == 0)) {
457                 /* As a special case, return /dev/null if we have been called for an empty data block */
458                 r = open("/dev/null", O_RDONLY|O_CLOEXEC|O_NOCTTY);
459                 if (r < 0)
460                         return -errno;
461
462                 return r;
463         }
464
465         if ((flags & ACQUIRE_NO_MEMFD) == 0) {
466                 fd = memfd_new("data-fd");
467                 if (fd < 0)
468                         goto try_pipe;
469
470                 n = write(fd, data, size);
471                 if (n < 0)
472                         return -errno;
473                 if ((size_t) n != size)
474                         return -EIO;
475
476                 f = lseek(fd, 0, SEEK_SET);
477                 if (f != 0)
478                         return -errno;
479
480                 r = memfd_set_sealed(fd);
481                 if (r < 0)
482                         return r;
483
484                 r = fd;
485                 fd = -1;
486
487                 return r;
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                 r = pipefds[0];
525                 pipefds[0] = -1;
526
527                 return r;
528         }
529
530 try_dev_shm:
531         if ((flags & ACQUIRE_NO_TMPFILE) == 0) {
532                 fd = open("/dev/shm", O_RDWR|O_TMPFILE|O_CLOEXEC, 0500);
533                 if (fd < 0)
534                         goto try_dev_shm_without_o_tmpfile;
535
536                 n = write(fd, data, size);
537                 if (n < 0)
538                         return -errno;
539                 if ((size_t) n != size)
540                         return -EIO;
541
542                 /* Let's reopen the thing, in order to get an O_RDONLY fd for the original O_RDWR one */
543                 xsprintf(procfs_path, "/proc/self/fd/%i", fd);
544                 r = open(procfs_path, O_RDONLY|O_CLOEXEC);
545                 if (r < 0)
546                         return -errno;
547
548                 return r;
549         }
550
551 try_dev_shm_without_o_tmpfile:
552         if ((flags & ACQUIRE_NO_REGULAR) == 0) {
553                 fd = mkostemp_safe(pattern);
554                 if (fd < 0)
555                         return fd;
556
557                 n = write(fd, data, size);
558                 if (n < 0) {
559                         r = -errno;
560                         goto unlink_and_return;
561                 }
562                 if ((size_t) n != size) {
563                         r = -EIO;
564                         goto unlink_and_return;
565                 }
566
567                 /* Let's reopen the thing, in order to get an O_RDONLY fd for the original O_RDWR one */
568                 r = open(pattern, O_RDONLY|O_CLOEXEC);
569                 if (r < 0)
570                         r = -errno;
571
572         unlink_and_return:
573                 (void) unlink(pattern);
574                 return r;
575         }
576
577         return -EOPNOTSUPP;
578 }
579
580 int fd_move_above_stdio(int fd) {
581         int flags, copy;
582         PROTECT_ERRNO;
583
584         /* Moves the specified file descriptor if possible out of the range [0…2], i.e. the range of
585          * stdin/stdout/stderr. If it can't be moved outside of this range the original file descriptor is
586          * returned. This call is supposed to be used for long-lasting file descriptors we allocate in our code that
587          * might get loaded into foreign code, and where we want ensure our fds are unlikely used accidentally as
588          * stdin/stdout/stderr of unrelated code.
589          *
590          * Note that this doesn't fix any real bugs, it just makes it less likely that our code will be affected by
591          * buggy code from others that mindlessly invokes 'fprintf(stderr, …' or similar in places where stderr has
592          * been closed before.
593          *
594          * This function is written in a "best-effort" and "least-impact" style. This means whenever we encounter an
595          * error we simply return the original file descriptor, and we do not touch errno. */
596
597         if (fd < 0 || fd > 2)
598                 return fd;
599
600         flags = fcntl(fd, F_GETFD, 0);
601         if (flags < 0)
602                 return fd;
603
604         if (flags & FD_CLOEXEC)
605                 copy = fcntl(fd, F_DUPFD_CLOEXEC, 3);
606         else
607                 copy = fcntl(fd, F_DUPFD, 3);
608         if (copy < 0)
609                 return fd;
610
611         assert(copy > 2);
612
613         (void) close(fd);
614         return copy;
615 }
616
617 int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd) {
618
619         int fd[3] = { /* Put together an array of fds we work on */
620                 original_input_fd,
621                 original_output_fd,
622                 original_error_fd
623         };
624
625         int r, i,
626                 null_fd = -1,                /* if we open /dev/null, we store the fd to it here */
627                 copy_fd[3] = { -1, -1, -1 }; /* This contains all fds we duplicate here temporarily, and hence need to close at the end */
628         bool null_readable, null_writable;
629
630         /* Sets up stdin, stdout, stderr with the three file descriptors passed in. If any of the descriptors is
631          * specified as -1 it will be connected with /dev/null instead. If any of the file descriptors is passed as
632          * itself (e.g. stdin as STDIN_FILENO) it is left unmodified, but the O_CLOEXEC bit is turned off should it be
633          * on.
634          *
635          * Note that if any of the passed file descriptors are > 2 they will be closed — both on success and on
636          * failure! Thus, callers should assume that when this function returns the input fds are invalidated.
637          *
638          * Note that when this function fails stdin/stdout/stderr might remain half set up!
639          *
640          * O_CLOEXEC is turned off for all three file descriptors (which is how it should be for
641          * stdin/stdout/stderr). */
642
643         null_readable = original_input_fd < 0;
644         null_writable = original_output_fd < 0 || original_error_fd < 0;
645
646         /* First step, open /dev/null once, if we need it */
647         if (null_readable || null_writable) {
648
649                 /* Let's open this with O_CLOEXEC first, and convert it to non-O_CLOEXEC when we move the fd to the final position. */
650                 null_fd = open("/dev/null", (null_readable && null_writable ? O_RDWR :
651                                              null_readable ? O_RDONLY : O_WRONLY) | O_CLOEXEC);
652                 if (null_fd < 0) {
653                         r = -errno;
654                         goto finish;
655                 }
656
657                 /* If this fd is in the 0…2 range, let's move it out of it */
658                 if (null_fd < 3) {
659                         int copy;
660
661                         copy = fcntl(null_fd, F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
662                         if (copy < 0) {
663                                 r = -errno;
664                                 goto finish;
665                         }
666
667                         safe_close(null_fd);
668                         null_fd = copy;
669                 }
670         }
671
672         /* Let's assemble fd[] with the fds to install in place of stdin/stdout/stderr */
673         for (i = 0; i < 3; i++) {
674
675                 if (fd[i] < 0)
676                         fd[i] = null_fd;        /* A negative parameter means: connect this one to /dev/null */
677                 else if (fd[i] != i && fd[i] < 3) {
678                         /* 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. */
679                         copy_fd[i] = fcntl(fd[i], F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
680                         if (copy_fd[i] < 0) {
681                                 r = -errno;
682                                 goto finish;
683                         }
684
685                         fd[i] = copy_fd[i];
686                 }
687         }
688
689         /* At this point we now have the fds to use in fd[], and they are all above the stdio range, so that we
690          * have freedom to move them around. If the fds already were at the right places then the specific fds are
691          * -1. Let's now move them to the right places. This is the point of no return. */
692         for (i = 0; i < 3; i++) {
693
694                 if (fd[i] == i) {
695
696                         /* fd is already in place, but let's make sure O_CLOEXEC is off */
697                         r = fd_cloexec(i, false);
698                         if (r < 0)
699                                 goto finish;
700
701                 } else {
702                         assert(fd[i] > 2);
703
704                         if (dup2(fd[i], i) < 0) { /* Turns off O_CLOEXEC on the new fd. */
705                                 r = -errno;
706                                 goto finish;
707                         }
708                 }
709         }
710
711         r = 0;
712
713 finish:
714         /* Close the original fds, but only if they were outside of the stdio range. Also, properly check for the same
715          * fd passed in multiple times. */
716         safe_close_above_stdio(original_input_fd);
717         if (original_output_fd != original_input_fd)
718                 safe_close_above_stdio(original_output_fd);
719         if (original_error_fd != original_input_fd && original_error_fd != original_output_fd)
720                 safe_close_above_stdio(original_error_fd);
721
722         /* Close the copies we moved > 2 */
723         for (i = 0; i < 3; i++)
724                 safe_close(copy_fd[i]);
725
726         /* Close our null fd, if it's > 2 */
727         safe_close_above_stdio(null_fd);
728
729         return r;
730 }