]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/fd-util.c
Merge pull request #2495 from heftig/master
[thirdparty/systemd.git] / src / basic / fd-util.c
CommitLineData
3ffd4af2
LP
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
11c3a366
TA
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
3ffd4af2 27#include "fd-util.h"
11c3a366
TA
28#include "macro.h"
29#include "missing.h"
93cc7779 30#include "parse-util.h"
11c3a366 31#include "path-util.h"
93cc7779 32#include "socket-util.h"
3ffd4af2
LP
33#include "util.h"
34
35int close_nointr(int fd) {
36 assert(fd >= 0);
37
38 if (close(fd) >= 0)
39 return 0;
40
41 /*
42 * Just ignore EINTR; a retry loop is the wrong thing to do on
43 * Linux.
44 *
45 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
46 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
47 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
48 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
49 */
50 if (errno == EINTR)
51 return 0;
52
53 return -errno;
54}
55
56int safe_close(int fd) {
57
58 /*
59 * Like close_nointr() but cannot fail. Guarantees errno is
60 * unchanged. Is a NOP with negative fds passed, and returns
61 * -1, so that it can be used in this syntax:
62 *
63 * fd = safe_close(fd);
64 */
65
66 if (fd >= 0) {
67 PROTECT_ERRNO;
68
69 /* The kernel might return pretty much any error code
70 * via close(), but the fd will be closed anyway. The
71 * only condition we want to check for here is whether
72 * the fd was invalid at all... */
73
74 assert_se(close_nointr(fd) != -EBADF);
75 }
76
77 return -1;
78}
79
80void safe_close_pair(int p[]) {
81 assert(p);
82
83 if (p[0] == p[1]) {
84 /* Special case pairs which use the same fd in both
85 * directions... */
86 p[0] = p[1] = safe_close(p[0]);
87 return;
88 }
89
90 p[0] = safe_close(p[0]);
91 p[1] = safe_close(p[1]);
92}
93
94void close_many(const int fds[], unsigned n_fd) {
95 unsigned i;
96
97 assert(fds || n_fd <= 0);
98
99 for (i = 0; i < n_fd; i++)
100 safe_close(fds[i]);
101}
102
103int fclose_nointr(FILE *f) {
104 assert(f);
105
106 /* Same as close_nointr(), but for fclose() */
107
108 if (fclose(f) == 0)
109 return 0;
110
111 if (errno == EINTR)
112 return 0;
113
114 return -errno;
115}
116
117FILE* safe_fclose(FILE *f) {
118
119 /* Same as safe_close(), but for fclose() */
120
121 if (f) {
122 PROTECT_ERRNO;
123
124 assert_se(fclose_nointr(f) != EBADF);
125 }
126
127 return NULL;
128}
129
130DIR* safe_closedir(DIR *d) {
131
132 if (d) {
133 PROTECT_ERRNO;
134
135 assert_se(closedir(d) >= 0 || errno != EBADF);
136 }
137
138 return NULL;
139}
140
141int fd_nonblock(int fd, bool nonblock) {
142 int flags, nflags;
143
144 assert(fd >= 0);
145
146 flags = fcntl(fd, F_GETFL, 0);
147 if (flags < 0)
148 return -errno;
149
150 if (nonblock)
151 nflags = flags | O_NONBLOCK;
152 else
153 nflags = flags & ~O_NONBLOCK;
154
155 if (nflags == flags)
156 return 0;
157
158 if (fcntl(fd, F_SETFL, nflags) < 0)
159 return -errno;
160
161 return 0;
162}
163
164int fd_cloexec(int fd, bool cloexec) {
165 int flags, nflags;
166
167 assert(fd >= 0);
168
169 flags = fcntl(fd, F_GETFD, 0);
170 if (flags < 0)
171 return -errno;
172
173 if (cloexec)
174 nflags = flags | FD_CLOEXEC;
175 else
176 nflags = flags & ~FD_CLOEXEC;
177
178 if (nflags == flags)
179 return 0;
180
181 if (fcntl(fd, F_SETFD, nflags) < 0)
182 return -errno;
183
184 return 0;
185}
186
187_pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
188 unsigned i;
189
190 assert(n_fdset == 0 || fdset);
191
192 for (i = 0; i < n_fdset; i++)
193 if (fdset[i] == fd)
194 return true;
195
196 return false;
197}
198
199int close_all_fds(const int except[], unsigned n_except) {
200 _cleanup_closedir_ DIR *d = NULL;
201 struct dirent *de;
202 int r = 0;
203
204 assert(n_except == 0 || except);
205
206 d = opendir("/proc/self/fd");
207 if (!d) {
208 int fd;
209 struct rlimit rl;
210
211 /* When /proc isn't available (for example in chroots)
212 * the fallback is brute forcing through the fd
213 * table */
214
215 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
216 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
217
218 if (fd_in_set(fd, except, n_except))
219 continue;
220
221 if (close_nointr(fd) < 0)
222 if (errno != EBADF && r == 0)
223 r = -errno;
224 }
225
226 return r;
227 }
228
229 while ((de = readdir(d))) {
230 int fd = -1;
231
232 if (hidden_file(de->d_name))
233 continue;
234
235 if (safe_atoi(de->d_name, &fd) < 0)
236 /* Let's better ignore this, just in case */
237 continue;
238
239 if (fd < 3)
240 continue;
241
242 if (fd == dirfd(d))
243 continue;
244
245 if (fd_in_set(fd, except, n_except))
246 continue;
247
248 if (close_nointr(fd) < 0) {
249 /* Valgrind has its own FD and doesn't want to have it closed */
250 if (errno != EBADF && r == 0)
251 r = -errno;
252 }
253 }
254
255 return r;
256}
257
258int 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();
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
323void 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}
4fee3975
LP
332
333bool 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}