chiark / gitweb /
8b7065fd5d53b8ab1fb30fe11fc53bda2d6250b0
[elogind.git] / src / basic / fd-util.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include "dirent-util.h"
23 #include "fd-util.h"
24 #include "parse-util.h"
25 #include "socket-util.h"
26 #include "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[], unsigned n_fd) {
88         unsigned 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 /// UNNEEDED by elogind
124 #if 0
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[], unsigned n_fdset) {
184         unsigned 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[], unsigned 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                 int fd;
205                 struct rlimit rl;
206
207                 /* When /proc isn't available (for example in chroots)
208                  * the fallback is brute forcing through the fd
209                  * table */
210
211                 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
212                 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
213
214                         if (fd_in_set(fd, except, n_except))
215                                 continue;
216
217                         if (close_nointr(fd) < 0)
218                                 if (errno != EBADF && r == 0)
219                                         r = -errno;
220                 }
221
222                 return r;
223         }
224
225         while ((de = readdir(d))) {
226                 int fd = -1;
227
228                 if (hidden_file(de->d_name))
229                         continue;
230
231                 if (safe_atoi(de->d_name, &fd) < 0)
232                         /* Let's better ignore this, just in case */
233                         continue;
234
235                 if (fd < 3)
236                         continue;
237
238                 if (fd == dirfd(d))
239                         continue;
240
241                 if (fd_in_set(fd, except, n_except))
242                         continue;
243
244                 if (close_nointr(fd) < 0) {
245                         /* Valgrind has its own FD and doesn't want to have it closed */
246                         if (errno != EBADF && r == 0)
247                                 r = -errno;
248                 }
249         }
250
251         return r;
252 }
253
254 /// UNNEEDED by elogind
255 #if 0
256 int same_fd(int a, int b) {
257         struct stat sta, stb;
258         pid_t pid;
259         int r, fa, fb;
260
261         assert(a >= 0);
262         assert(b >= 0);
263
264         /* Compares two file descriptors. Note that semantics are
265          * quite different depending on whether we have kcmp() or we
266          * don't. If we have kcmp() this will only return true for
267          * dup()ed file descriptors, but not otherwise. If we don't
268          * have kcmp() this will also return true for two fds of the same
269          * file, created by separate open() calls. Since we use this
270          * call mostly for filtering out duplicates in the fd store
271          * this difference hopefully doesn't matter too much. */
272
273         if (a == b)
274                 return true;
275
276         /* Try to use kcmp() if we have it. */
277         pid = getpid();
278         r = kcmp(pid, pid, KCMP_FILE, a, b);
279         if (r == 0)
280                 return true;
281         if (r > 0)
282                 return false;
283         if (errno != ENOSYS)
284                 return -errno;
285
286         /* We don't have kcmp(), use fstat() instead. */
287         if (fstat(a, &sta) < 0)
288                 return -errno;
289
290         if (fstat(b, &stb) < 0)
291                 return -errno;
292
293         if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
294                 return false;
295
296         /* We consider all device fds different, since two device fds
297          * might refer to quite different device contexts even though
298          * they share the same inode and backing dev_t. */
299
300         if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
301                 return false;
302
303         if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
304                 return false;
305
306         /* The fds refer to the same inode on disk, let's also check
307          * if they have the same fd flags. This is useful to
308          * distinguish the read and write side of a pipe created with
309          * pipe(). */
310         fa = fcntl(a, F_GETFL);
311         if (fa < 0)
312                 return -errno;
313
314         fb = fcntl(b, F_GETFL);
315         if (fb < 0)
316                 return -errno;
317
318         return fa == fb;
319 }
320
321 void cmsg_close_all(struct msghdr *mh) {
322         struct cmsghdr *cmsg;
323
324         assert(mh);
325
326         CMSG_FOREACH(cmsg, mh)
327                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
328                         close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
329 }
330
331 bool fdname_is_valid(const char *s) {
332         const char *p;
333
334         /* Validates a name for $LISTEN_FDNAMES. We basically allow
335          * everything ASCII that's not a control character. Also, as
336          * special exception the ":" character is not allowed, as we
337          * use that as field separator in $LISTEN_FDNAMES.
338          *
339          * Note that the empty string is explicitly allowed
340          * here. However, we limit the length of the names to 255
341          * characters. */
342
343         if (!s)
344                 return false;
345
346         for (p = s; *p; p++) {
347                 if (*p < ' ')
348                         return false;
349                 if (*p >= 127)
350                         return false;
351                 if (*p == ':')
352                         return false;
353         }
354
355         return p - s < 256;
356 }
357 #endif // 0