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