chiark / gitweb /
Prep v233: Add missing includes in src/shared
[elogind.git] / src / basic / fd-util.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2010 Lennart Poettering
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <sys/resource.h>
23 #include <sys/socket.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26
27 #include "dirent-util.h"
28 #include "fd-util.h"
29 #include "macro.h"
30 #include "missing.h"
31 #include "parse-util.h"
32 #include "path-util.h"
33 #include "socket-util.h"
34 #include "util.h"
35
36 int close_nointr(int fd) {
37         assert(fd >= 0);
38
39         if (close(fd) >= 0)
40                 return 0;
41
42         /*
43          * Just ignore EINTR; a retry loop is the wrong thing to do on
44          * Linux.
45          *
46          * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
47          * https://bugzilla.gnome.org/show_bug.cgi?id=682819
48          * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
49          * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
50          */
51         if (errno == EINTR)
52                 return 0;
53
54         return -errno;
55 }
56
57 int safe_close(int fd) {
58
59         /*
60          * Like close_nointr() but cannot fail. Guarantees errno is
61          * unchanged. Is a NOP with negative fds passed, and returns
62          * -1, so that it can be used in this syntax:
63          *
64          * fd = safe_close(fd);
65          */
66
67         if (fd >= 0) {
68                 PROTECT_ERRNO;
69
70                 /* The kernel might return pretty much any error code
71                  * via close(), but the fd will be closed anyway. The
72                  * only condition we want to check for here is whether
73                  * the fd was invalid at all... */
74
75                 assert_se(close_nointr(fd) != -EBADF);
76         }
77
78         return -1;
79 }
80
81 void safe_close_pair(int p[]) {
82         assert(p);
83
84         if (p[0] == p[1]) {
85                 /* Special case pairs which use the same fd in both
86                  * directions... */
87                 p[0] = p[1] = safe_close(p[0]);
88                 return;
89         }
90
91         p[0] = safe_close(p[0]);
92         p[1] = safe_close(p[1]);
93 }
94
95 void close_many(const int fds[], unsigned n_fd) {
96         unsigned i;
97
98         assert(fds || n_fd <= 0);
99
100         for (i = 0; i < n_fd; i++)
101                 safe_close(fds[i]);
102 }
103
104 int fclose_nointr(FILE *f) {
105         assert(f);
106
107         /* Same as close_nointr(), but for fclose() */
108
109         if (fclose(f) == 0)
110                 return 0;
111
112         if (errno == EINTR)
113                 return 0;
114
115         return -errno;
116 }
117
118 FILE* safe_fclose(FILE *f) {
119
120         /* Same as safe_close(), but for fclose() */
121
122         if (f) {
123                 PROTECT_ERRNO;
124
125                 assert_se(fclose_nointr(f) != EBADF);
126         }
127
128         return NULL;
129 }
130
131 #if 0 /// UNNEEDED by elogind
132 DIR* safe_closedir(DIR *d) {
133
134         if (d) {
135                 PROTECT_ERRNO;
136
137                 assert_se(closedir(d) >= 0 || errno != EBADF);
138         }
139
140         return NULL;
141 }
142 #endif // 0
143
144 int fd_nonblock(int fd, bool nonblock) {
145         int flags, nflags;
146
147         assert(fd >= 0);
148
149         flags = fcntl(fd, F_GETFL, 0);
150         if (flags < 0)
151                 return -errno;
152
153         if (nonblock)
154                 nflags = flags | O_NONBLOCK;
155         else
156                 nflags = flags & ~O_NONBLOCK;
157
158         if (nflags == flags)
159                 return 0;
160
161         if (fcntl(fd, F_SETFL, nflags) < 0)
162                 return -errno;
163
164         return 0;
165 }
166
167 int fd_cloexec(int fd, bool cloexec) {
168         int flags, nflags;
169
170         assert(fd >= 0);
171
172         flags = fcntl(fd, F_GETFD, 0);
173         if (flags < 0)
174                 return -errno;
175
176         if (cloexec)
177                 nflags = flags | FD_CLOEXEC;
178         else
179                 nflags = flags & ~FD_CLOEXEC;
180
181         if (nflags == flags)
182                 return 0;
183
184         if (fcntl(fd, F_SETFD, nflags) < 0)
185                 return -errno;
186
187         return 0;
188 }
189
190 void stdio_unset_cloexec(void) {
191         fd_cloexec(STDIN_FILENO, false);
192         fd_cloexec(STDOUT_FILENO, false);
193         fd_cloexec(STDERR_FILENO, false);
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
227                         if (fd_in_set(fd, except, n_except))
228                                 continue;
229
230                         if (close_nointr(fd) < 0)
231                                 if (errno != EBADF && r == 0)
232                                         r = -errno;
233                 }
234
235                 return r;
236         }
237
238         FOREACH_DIRENT(de, d, return -errno) {
239                 int fd = -1;
240
241                 if (safe_atoi(de->d_name, &fd) < 0)
242                         /* Let's better ignore this, just in case */
243                         continue;
244
245                 if (fd < 3)
246                         continue;
247
248                 if (fd == dirfd(d))
249                         continue;
250
251                 if (fd_in_set(fd, except, n_except))
252                         continue;
253
254                 if (close_nointr(fd) < 0) {
255                         /* Valgrind has its own FD and doesn't want to have it closed */
256                         if (errno != EBADF && r == 0)
257                                 r = -errno;
258                 }
259         }
260
261         return r;
262 }
263
264 #if 0 /// UNNEEDED by elogind
265 int same_fd(int a, int b) {
266         struct stat sta, stb;
267         pid_t pid;
268         int r, fa, fb;
269
270         assert(a >= 0);
271         assert(b >= 0);
272
273         /* Compares two file descriptors. Note that semantics are
274          * quite different depending on whether we have kcmp() or we
275          * don't. If we have kcmp() this will only return true for
276          * dup()ed file descriptors, but not otherwise. If we don't
277          * have kcmp() this will also return true for two fds of the same
278          * file, created by separate open() calls. Since we use this
279          * call mostly for filtering out duplicates in the fd store
280          * this difference hopefully doesn't matter too much. */
281
282         if (a == b)
283                 return true;
284
285         /* Try to use kcmp() if we have it. */
286         pid = getpid();
287         r = kcmp(pid, pid, KCMP_FILE, a, b);
288         if (r == 0)
289                 return true;
290         if (r > 0)
291                 return false;
292         if (errno != ENOSYS)
293                 return -errno;
294
295         /* We don't have kcmp(), use fstat() instead. */
296         if (fstat(a, &sta) < 0)
297                 return -errno;
298
299         if (fstat(b, &stb) < 0)
300                 return -errno;
301
302         if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
303                 return false;
304
305         /* We consider all device fds different, since two device fds
306          * might refer to quite different device contexts even though
307          * they share the same inode and backing dev_t. */
308
309         if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
310                 return false;
311
312         if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
313                 return false;
314
315         /* The fds refer to the same inode on disk, let's also check
316          * if they have the same fd flags. This is useful to
317          * distinguish the read and write side of a pipe created with
318          * pipe(). */
319         fa = fcntl(a, F_GETFL);
320         if (fa < 0)
321                 return -errno;
322
323         fb = fcntl(b, F_GETFL);
324         if (fb < 0)
325                 return -errno;
326
327         return fa == fb;
328 }
329
330 void cmsg_close_all(struct msghdr *mh) {
331         struct cmsghdr *cmsg;
332
333         assert(mh);
334
335         CMSG_FOREACH(cmsg, mh)
336                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
337                         close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
338 }
339
340 bool fdname_is_valid(const char *s) {
341         const char *p;
342
343         /* Validates a name for $LISTEN_FDNAMES. We basically allow
344          * everything ASCII that's not a control character. Also, as
345          * special exception the ":" character is not allowed, as we
346          * use that as field separator in $LISTEN_FDNAMES.
347          *
348          * Note that the empty string is explicitly allowed
349          * here. However, we limit the length of the names to 255
350          * characters. */
351
352         if (!s)
353                 return false;
354
355         for (p = s; *p; p++) {
356                 if (*p < ' ')
357                         return false;
358                 if (*p >= 127)
359                         return false;
360                 if (*p == ':')
361                         return false;
362         }
363
364         return p - s < 256;
365 }
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 #endif // 0