]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/fd-util.c
Merge pull request #5276 from poettering/resolved-cname
[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
8fb3f009 27#include "dirent-util.h"
3ffd4af2 28#include "fd-util.h"
4aeb20f5 29#include "fs-util.h"
11c3a366
TA
30#include "macro.h"
31#include "missing.h"
93cc7779 32#include "parse-util.h"
11c3a366 33#include "path-util.h"
93cc7779 34#include "socket-util.h"
4aeb20f5 35#include "stdio-util.h"
3ffd4af2
LP
36#include "util.h"
37
38int close_nointr(int fd) {
39 assert(fd >= 0);
40
41 if (close(fd) >= 0)
42 return 0;
43
44 /*
45 * Just ignore EINTR; a retry loop is the wrong thing to do on
46 * Linux.
47 *
48 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
49 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
50 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
51 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
52 */
53 if (errno == EINTR)
54 return 0;
55
56 return -errno;
57}
58
59int safe_close(int fd) {
60
61 /*
62 * Like close_nointr() but cannot fail. Guarantees errno is
63 * unchanged. Is a NOP with negative fds passed, and returns
64 * -1, so that it can be used in this syntax:
65 *
66 * fd = safe_close(fd);
67 */
68
69 if (fd >= 0) {
70 PROTECT_ERRNO;
71
72 /* The kernel might return pretty much any error code
73 * via close(), but the fd will be closed anyway. The
74 * only condition we want to check for here is whether
75 * the fd was invalid at all... */
76
77 assert_se(close_nointr(fd) != -EBADF);
78 }
79
80 return -1;
81}
82
83void safe_close_pair(int p[]) {
84 assert(p);
85
86 if (p[0] == p[1]) {
87 /* Special case pairs which use the same fd in both
88 * directions... */
89 p[0] = p[1] = safe_close(p[0]);
90 return;
91 }
92
93 p[0] = safe_close(p[0]);
94 p[1] = safe_close(p[1]);
95}
96
97void close_many(const int fds[], unsigned n_fd) {
98 unsigned i;
99
100 assert(fds || n_fd <= 0);
101
102 for (i = 0; i < n_fd; i++)
103 safe_close(fds[i]);
104}
105
106int fclose_nointr(FILE *f) {
107 assert(f);
108
109 /* Same as close_nointr(), but for fclose() */
110
111 if (fclose(f) == 0)
112 return 0;
113
114 if (errno == EINTR)
115 return 0;
116
117 return -errno;
118}
119
120FILE* safe_fclose(FILE *f) {
121
122 /* Same as safe_close(), but for fclose() */
123
124 if (f) {
125 PROTECT_ERRNO;
126
127 assert_se(fclose_nointr(f) != EBADF);
128 }
129
130 return NULL;
131}
132
133DIR* safe_closedir(DIR *d) {
134
135 if (d) {
136 PROTECT_ERRNO;
137
138 assert_se(closedir(d) >= 0 || errno != EBADF);
139 }
140
141 return NULL;
142}
143
144int 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
167int 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
3b9a1d87
AK
190void stdio_unset_cloexec(void) {
191 fd_cloexec(STDIN_FILENO, false);
192 fd_cloexec(STDOUT_FILENO, false);
193 fd_cloexec(STDERR_FILENO, false);
194}
195
3ffd4af2
LP
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
208int 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
8fb3f009 238 FOREACH_DIRENT(de, d, return -errno) {
3ffd4af2
LP
239 int fd = -1;
240
3ffd4af2
LP
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
264int 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();
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
329void 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}
4fee3975
LP
338
339bool 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}
4aeb20f5
LP
365
366int fd_get_path(int fd, char **ret) {
367 char procfs_path[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
a0fe2a2d 368 int r;
4aeb20f5
LP
369
370 xsprintf(procfs_path, "/proc/self/fd/%i", fd);
371
a0fe2a2d
LP
372 r = readlink_malloc(procfs_path, ret);
373
374 if (r == -ENOENT) /* If the file doesn't exist the fd is invalid */
375 return -EBADF;
376
377 return r;
4aeb20f5 378}