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