]>
Commit | Line | Data |
---|---|---|
db9ecf05 | 1 | /* SPDX-License-Identifier: LGPL-2.1-or-later */ |
3ffd4af2 | 2 | |
11c3a366 TA |
3 | #include <errno.h> |
4 | #include <fcntl.h> | |
3657d3a0 | 5 | #if WANT_LINUX_FS_H |
7e93a658 | 6 | #include <linux/fs.h> |
3657d3a0 | 7 | #endif |
65ddc2c5 ZJS |
8 | #include <linux/magic.h> |
9 | #include <sys/ioctl.h> | |
11c3a366 | 10 | #include <sys/resource.h> |
11c3a366 TA |
11 | #include <sys/stat.h> |
12 | #include <unistd.h> | |
13 | ||
4960ce43 | 14 | #include "alloc-util.h" |
8fb3f009 | 15 | #include "dirent-util.h" |
3ffd4af2 | 16 | #include "fd-util.h" |
a548e14d | 17 | #include "fileio.h" |
4aeb20f5 | 18 | #include "fs-util.h" |
4960ce43 | 19 | #include "io-util.h" |
11c3a366 | 20 | #include "macro.h" |
0499585f | 21 | #include "missing_fcntl.h" |
7e93a658 | 22 | #include "missing_fs.h" |
f5947a5e | 23 | #include "missing_syscall.h" |
af423b4b | 24 | #include "mountpoint-util.h" |
93cc7779 | 25 | #include "parse-util.h" |
11c3a366 | 26 | #include "path-util.h" |
df0ff127 | 27 | #include "process-util.h" |
93cc7779 | 28 | #include "socket-util.h" |
b8cfa2da | 29 | #include "sort-util.h" |
f8606626 | 30 | #include "stat-util.h" |
4aeb20f5 | 31 | #include "stdio-util.h" |
e4de7287 | 32 | #include "tmpfile-util.h" |
3ffd4af2 | 33 | |
6a461d1f ZJS |
34 | /* The maximum number of iterations in the loop to close descriptors in the fallback case |
35 | * when /proc/self/fd/ is inaccessible. */ | |
36 | #define MAX_FD_LOOP_LIMIT (1024*1024) | |
37 | ||
3ffd4af2 LP |
38 | int 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 | ||
59 | int safe_close(int fd) { | |
3ffd4af2 | 60 | /* |
254d1313 ZJS |
61 | * Like close_nointr() but cannot fail. Guarantees errno is unchanged. Is a noop for negative fds, |
62 | * and returns -EBADF, so that it can be used in this syntax: | |
3ffd4af2 LP |
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 | ||
254d1313 | 78 | return -EBADF; |
3ffd4af2 LP |
79 | } |
80 | ||
3042bbeb | 81 | void safe_close_pair(int p[static 2]) { |
3ffd4af2 LP |
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 | ||
da6053d0 | 95 | void close_many(const int fds[], size_t n_fd) { |
3ffd4af2 LP |
96 | assert(fds || n_fd <= 0); |
97 | ||
fe96c0f8 | 98 | for (size_t i = 0; i < n_fd; i++) |
3ffd4af2 LP |
99 | safe_close(fds[i]); |
100 | } | |
101 | ||
102 | int fclose_nointr(FILE *f) { | |
103 | assert(f); | |
104 | ||
105 | /* Same as close_nointr(), but for fclose() */ | |
106 | ||
75f6d5d8 LP |
107 | errno = 0; /* Extra safety: if the FILE* object is not encapsulating an fd, it might not set errno |
108 | * correctly. Let's hence initialize it to zero first, so that we aren't confused by any | |
109 | * prior errno here */ | |
3ffd4af2 LP |
110 | if (fclose(f) == 0) |
111 | return 0; | |
112 | ||
113 | if (errno == EINTR) | |
114 | return 0; | |
115 | ||
75f6d5d8 | 116 | return errno_or_else(EIO); |
3ffd4af2 LP |
117 | } |
118 | ||
119 | FILE* safe_fclose(FILE *f) { | |
120 | ||
121 | /* Same as safe_close(), but for fclose() */ | |
122 | ||
123 | if (f) { | |
124 | PROTECT_ERRNO; | |
125 | ||
6dce3bb4 | 126 | assert_se(fclose_nointr(f) != -EBADF); |
3ffd4af2 LP |
127 | } |
128 | ||
129 | return NULL; | |
130 | } | |
131 | ||
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 | ||
143 | int fd_nonblock(int fd, bool nonblock) { | |
144 | int flags, nflags; | |
145 | ||
146 | assert(fd >= 0); | |
147 | ||
148 | flags = fcntl(fd, F_GETFL, 0); | |
149 | if (flags < 0) | |
150 | return -errno; | |
151 | ||
0da96503 | 152 | nflags = UPDATE_FLAG(flags, O_NONBLOCK, nonblock); |
3ffd4af2 LP |
153 | if (nflags == flags) |
154 | return 0; | |
155 | ||
7c248223 | 156 | return RET_NERRNO(fcntl(fd, F_SETFL, nflags)); |
3ffd4af2 LP |
157 | } |
158 | ||
159 | int fd_cloexec(int fd, bool cloexec) { | |
160 | int flags, nflags; | |
161 | ||
162 | assert(fd >= 0); | |
163 | ||
164 | flags = fcntl(fd, F_GETFD, 0); | |
165 | if (flags < 0) | |
166 | return -errno; | |
167 | ||
0da96503 | 168 | nflags = UPDATE_FLAG(flags, FD_CLOEXEC, cloexec); |
3ffd4af2 LP |
169 | if (nflags == flags) |
170 | return 0; | |
171 | ||
7c248223 | 172 | return RET_NERRNO(fcntl(fd, F_SETFD, nflags)); |
3ffd4af2 LP |
173 | } |
174 | ||
ed18c22c LP |
175 | int fd_cloexec_many(const int fds[], size_t n_fds, bool cloexec) { |
176 | int ret = 0, r; | |
177 | ||
178 | assert(n_fds == 0 || fds); | |
179 | ||
180 | for (size_t i = 0; i < n_fds; i++) { | |
181 | if (fds[i] < 0) /* Skip gracefully over already invalidated fds */ | |
182 | continue; | |
183 | ||
184 | r = fd_cloexec(fds[i], cloexec); | |
185 | if (r < 0 && ret >= 0) /* Continue going, but return first error */ | |
186 | ret = r; | |
187 | else | |
188 | ret = 1; /* report if we did anything */ | |
189 | } | |
190 | ||
191 | return ret; | |
192 | } | |
193 | ||
da6053d0 | 194 | _pure_ static bool fd_in_set(int fd, const int fdset[], size_t n_fdset) { |
3ffd4af2 LP |
195 | assert(n_fdset == 0 || fdset); |
196 | ||
d11c14a9 LP |
197 | for (size_t i = 0; i < n_fdset; i++) { |
198 | if (fdset[i] < 0) | |
199 | continue; | |
200 | ||
3ffd4af2 LP |
201 | if (fdset[i] == fd) |
202 | return true; | |
d11c14a9 | 203 | } |
3ffd4af2 LP |
204 | |
205 | return false; | |
206 | } | |
207 | ||
73fc0cbc | 208 | int get_max_fd(void) { |
498e265d LP |
209 | struct rlimit rl; |
210 | rlim_t m; | |
211 | ||
212 | /* Return the highest possible fd, based RLIMIT_NOFILE, but enforcing FD_SETSIZE-1 as lower boundary | |
213 | * and INT_MAX as upper boundary. */ | |
214 | ||
215 | if (getrlimit(RLIMIT_NOFILE, &rl) < 0) | |
216 | return -errno; | |
217 | ||
218 | m = MAX(rl.rlim_cur, rl.rlim_max); | |
219 | if (m < FD_SETSIZE) /* Let's always cover at least 1024 fds */ | |
220 | return FD_SETSIZE-1; | |
221 | ||
222 | if (m == RLIM_INFINITY || m > INT_MAX) /* Saturate on overflow. After all fds are "int", hence can | |
223 | * never be above INT_MAX */ | |
224 | return INT_MAX; | |
225 | ||
226 | return (int) (m - 1); | |
227 | } | |
228 | ||
5cfa0798 | 229 | static int close_all_fds_frugal(const int except[], size_t n_except) { |
11966552 LP |
230 | int max_fd, r = 0; |
231 | ||
232 | assert(n_except == 0 || except); | |
233 | ||
234 | /* This is the inner fallback core of close_all_fds(). This never calls malloc() or opendir() or so | |
235 | * and hence is safe to be called in signal handler context. Most users should call close_all_fds(), | |
236 | * but when we assume we are called from signal handler context, then use this simpler call | |
237 | * instead. */ | |
238 | ||
239 | max_fd = get_max_fd(); | |
240 | if (max_fd < 0) | |
241 | return max_fd; | |
242 | ||
243 | /* Refuse to do the loop over more too many elements. It's better to fail immediately than to | |
244 | * spin the CPU for a long time. */ | |
245 | if (max_fd > MAX_FD_LOOP_LIMIT) | |
246 | return log_debug_errno(SYNTHETIC_ERRNO(EPERM), | |
247 | "Refusing to loop over %d potential fds.", | |
248 | max_fd); | |
249 | ||
5bb1d7fb | 250 | for (int fd = 3; fd >= 0; fd = fd < max_fd ? fd + 1 : -EBADF) { |
11966552 LP |
251 | int q; |
252 | ||
253 | if (fd_in_set(fd, except, n_except)) | |
254 | continue; | |
255 | ||
256 | q = close_nointr(fd); | |
257 | if (q < 0 && q != -EBADF && r >= 0) | |
258 | r = q; | |
259 | } | |
260 | ||
261 | return r; | |
262 | } | |
263 | ||
5cfa0798 | 264 | static bool have_close_range = true; /* Assume we live in the future */ |
3ffd4af2 | 265 | |
5cfa0798 | 266 | static int close_all_fds_special_case(const int except[], size_t n_except) { |
3ffd4af2 LP |
267 | assert(n_except == 0 || except); |
268 | ||
5cfa0798 LP |
269 | /* Handles a few common special cases separately, since they are common and can be optimized really |
270 | * nicely, since we won't need sorting for them. Returns > 0 if the special casing worked, 0 | |
271 | * otherwise. */ | |
b8cfa2da | 272 | |
5cfa0798 LP |
273 | if (!have_close_range) |
274 | return 0; | |
b8cfa2da | 275 | |
d11c14a9 LP |
276 | if (n_except == 1 && except[0] < 0) /* Minor optimization: if we only got one fd, and it's invalid, |
277 | * we got none */ | |
278 | n_except = 0; | |
279 | ||
5cfa0798 | 280 | switch (n_except) { |
b8cfa2da | 281 | |
5cfa0798 LP |
282 | case 0: |
283 | /* Close everything. Yay! */ | |
b8cfa2da | 284 | |
5cfa0798 LP |
285 | if (close_range(3, -1, 0) >= 0) |
286 | return 1; | |
f498720a | 287 | |
5cfa0798 LP |
288 | if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) { |
289 | have_close_range = false; | |
290 | return 0; | |
291 | } | |
f498720a | 292 | |
5cfa0798 | 293 | return -errno; |
f498720a | 294 | |
5cfa0798 LP |
295 | case 1: |
296 | /* Close all but exactly one, then we don't need no sorting. This is a pretty common | |
297 | * case, hence let's handle it specially. */ | |
f498720a | 298 | |
5cfa0798 LP |
299 | if ((except[0] <= 3 || close_range(3, except[0]-1, 0) >= 0) && |
300 | (except[0] >= INT_MAX || close_range(MAX(3, except[0]+1), -1, 0) >= 0)) | |
301 | return 1; | |
f498720a | 302 | |
5cfa0798 | 303 | if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) { |
f498720a | 304 | have_close_range = false; |
5cfa0798 LP |
305 | return 0; |
306 | } | |
f498720a | 307 | |
5cfa0798 | 308 | return -errno; |
c85cb3bc | 309 | |
5cfa0798 LP |
310 | default: |
311 | return 0; | |
312 | } | |
313 | } | |
c85cb3bc | 314 | |
5cfa0798 LP |
315 | int close_all_fds_without_malloc(const int except[], size_t n_except) { |
316 | int r; | |
c85cb3bc | 317 | |
5cfa0798 | 318 | assert(n_except == 0 || except); |
c85cb3bc | 319 | |
5cfa0798 LP |
320 | r = close_all_fds_special_case(except, n_except); |
321 | if (r < 0) | |
322 | return r; | |
323 | if (r > 0) /* special case worked! */ | |
324 | return 0; | |
b8cfa2da | 325 | |
5cfa0798 LP |
326 | return close_all_fds_frugal(except, n_except); |
327 | } | |
b8cfa2da | 328 | |
5cfa0798 LP |
329 | int close_all_fds(const int except[], size_t n_except) { |
330 | _cleanup_closedir_ DIR *d = NULL; | |
5cfa0798 LP |
331 | int r = 0; |
332 | ||
333 | assert(n_except == 0 || except); | |
334 | ||
335 | r = close_all_fds_special_case(except, n_except); | |
336 | if (r < 0) | |
337 | return r; | |
338 | if (r > 0) /* special case worked! */ | |
339 | return 0; | |
340 | ||
341 | if (have_close_range) { | |
342 | _cleanup_free_ int *sorted_malloc = NULL; | |
343 | size_t n_sorted; | |
344 | int *sorted; | |
345 | ||
346 | /* In the best case we have close_range() to close all fds between a start and an end fd, | |
347 | * which we can use on the "inverted" exception array, i.e. all intervals between all | |
348 | * adjacent pairs from the sorted exception array. This changes loop complexity from O(n) | |
349 | * where n is number of open fds to O(m⋅log(m)) where m is the number of fds to keep | |
350 | * open. Given that we assume n ≫ m that's preferable to us. */ | |
b8cfa2da | 351 | |
5cfa0798 LP |
352 | assert(n_except < SIZE_MAX); |
353 | n_sorted = n_except + 1; | |
c85cb3bc | 354 | |
5cfa0798 LP |
355 | if (n_sorted > 64) /* Use heap for large numbers of fds, stack otherwise */ |
356 | sorted = sorted_malloc = new(int, n_sorted); | |
357 | else | |
358 | sorted = newa(int, n_sorted); | |
c85cb3bc | 359 | |
5cfa0798 LP |
360 | if (sorted) { |
361 | memcpy(sorted, except, n_except * sizeof(int)); | |
c85cb3bc | 362 | |
5cfa0798 LP |
363 | /* Let's add fd 2 to the list of fds, to simplify the loop below, as this |
364 | * allows us to cover the head of the array the same way as the body */ | |
365 | sorted[n_sorted-1] = 2; | |
b8cfa2da | 366 | |
5cfa0798 LP |
367 | typesafe_qsort(sorted, n_sorted, cmp_int); |
368 | ||
369 | for (size_t i = 0; i < n_sorted-1; i++) { | |
370 | int start, end; | |
b8cfa2da | 371 | |
5cfa0798 LP |
372 | start = MAX(sorted[i], 2); /* The first three fds shall always remain open */ |
373 | end = MAX(sorted[i+1], 2); | |
b8cfa2da | 374 | |
5cfa0798 | 375 | assert(end >= start); |
b8cfa2da | 376 | |
5cfa0798 LP |
377 | if (end - start <= 1) |
378 | continue; | |
b8cfa2da | 379 | |
5cfa0798 LP |
380 | /* Close everything between the start and end fds (both of which shall stay open) */ |
381 | if (close_range(start + 1, end - 1, 0) < 0) { | |
c85cb3bc LP |
382 | if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) |
383 | return -errno; | |
b8cfa2da | 384 | |
c85cb3bc | 385 | have_close_range = false; |
5cfa0798 | 386 | break; |
c85cb3bc LP |
387 | } |
388 | } | |
5cfa0798 LP |
389 | |
390 | if (have_close_range) { | |
391 | /* The loop succeeded. Let's now close everything beyond the end */ | |
392 | ||
393 | if (sorted[n_sorted-1] >= INT_MAX) /* Dont let the addition below overflow */ | |
394 | return 0; | |
395 | ||
396 | if (close_range(sorted[n_sorted-1] + 1, -1, 0) >= 0) | |
397 | return 0; | |
398 | ||
399 | if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) | |
400 | return -errno; | |
401 | ||
402 | have_close_range = false; | |
403 | } | |
b8cfa2da | 404 | } |
c85cb3bc LP |
405 | |
406 | /* Fallback on OOM or if close_range() is not supported */ | |
b8cfa2da LP |
407 | } |
408 | ||
e7e7c07c | 409 | d = opendir("/proc/self/fd"); |
11966552 | 410 | if (!d) |
5cfa0798 | 411 | return close_all_fds_frugal(except, n_except); /* ultimate fallback if /proc/ is not available */ |
3ffd4af2 | 412 | |
c85cb3bc | 413 | FOREACH_DIRENT(de, d, return -errno) { |
254d1313 | 414 | int fd = -EBADF, q; |
3ffd4af2 | 415 | |
1f6639ea LP |
416 | if (!IN_SET(de->d_type, DT_LNK, DT_UNKNOWN)) |
417 | continue; | |
418 | ||
e652663a DT |
419 | fd = parse_fd(de->d_name); |
420 | if (fd < 0) | |
c85cb3bc LP |
421 | /* Let's better ignore this, just in case */ |
422 | continue; | |
3ffd4af2 | 423 | |
c85cb3bc LP |
424 | if (fd < 3) |
425 | continue; | |
3ffd4af2 | 426 | |
c85cb3bc LP |
427 | if (fd == dirfd(d)) |
428 | continue; | |
3ffd4af2 LP |
429 | |
430 | if (fd_in_set(fd, except, n_except)) | |
431 | continue; | |
432 | ||
e43bc9f5 | 433 | q = close_nointr(fd); |
c85cb3bc | 434 | if (q < 0 && q != -EBADF && r >= 0) /* Valgrind has its own FD and doesn't want to have it closed */ |
e43bc9f5 | 435 | r = q; |
3ffd4af2 LP |
436 | } |
437 | ||
438 | return r; | |
439 | } | |
440 | ||
441 | int same_fd(int a, int b) { | |
442 | struct stat sta, stb; | |
443 | pid_t pid; | |
444 | int r, fa, fb; | |
445 | ||
446 | assert(a >= 0); | |
447 | assert(b >= 0); | |
448 | ||
675e7fc2 LP |
449 | /* Compares two file descriptors. Note that semantics are quite different depending on whether we |
450 | * have kcmp() or we don't. If we have kcmp() this will only return true for dup()ed file | |
451 | * descriptors, but not otherwise. If we don't have kcmp() this will also return true for two fds of | |
452 | * the same file, created by separate open() calls. Since we use this call mostly for filtering out | |
453 | * duplicates in the fd store this difference hopefully doesn't matter too much. */ | |
3ffd4af2 LP |
454 | |
455 | if (a == b) | |
456 | return true; | |
457 | ||
458 | /* Try to use kcmp() if we have it. */ | |
df0ff127 | 459 | pid = getpid_cached(); |
3ffd4af2 LP |
460 | r = kcmp(pid, pid, KCMP_FILE, a, b); |
461 | if (r == 0) | |
462 | return true; | |
463 | if (r > 0) | |
464 | return false; | |
675e7fc2 | 465 | if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) |
3ffd4af2 LP |
466 | return -errno; |
467 | ||
468 | /* We don't have kcmp(), use fstat() instead. */ | |
469 | if (fstat(a, &sta) < 0) | |
470 | return -errno; | |
471 | ||
472 | if (fstat(b, &stb) < 0) | |
473 | return -errno; | |
474 | ||
a9dac7a6 | 475 | if (!stat_inode_same(&sta, &stb)) |
3ffd4af2 LP |
476 | return false; |
477 | ||
675e7fc2 LP |
478 | /* We consider all device fds different, since two device fds might refer to quite different device |
479 | * contexts even though they share the same inode and backing dev_t. */ | |
3ffd4af2 LP |
480 | |
481 | if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode)) | |
482 | return false; | |
483 | ||
a9dac7a6 LP |
484 | /* The fds refer to the same inode on disk, let's also check if they have the same fd flags. This is |
485 | * useful to distinguish the read and write side of a pipe created with pipe(). */ | |
3ffd4af2 LP |
486 | fa = fcntl(a, F_GETFL); |
487 | if (fa < 0) | |
488 | return -errno; | |
489 | ||
490 | fb = fcntl(b, F_GETFL); | |
491 | if (fb < 0) | |
492 | return -errno; | |
493 | ||
494 | return fa == fb; | |
495 | } | |
496 | ||
497 | void cmsg_close_all(struct msghdr *mh) { | |
498 | struct cmsghdr *cmsg; | |
499 | ||
500 | assert(mh); | |
501 | ||
502 | CMSG_FOREACH(cmsg, mh) | |
503 | if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) | |
6759b627 TH |
504 | close_many(CMSG_TYPED_DATA(cmsg, int), |
505 | (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int)); | |
3ffd4af2 | 506 | } |
4fee3975 LP |
507 | |
508 | bool fdname_is_valid(const char *s) { | |
509 | const char *p; | |
510 | ||
511 | /* Validates a name for $LISTEN_FDNAMES. We basically allow | |
512 | * everything ASCII that's not a control character. Also, as | |
513 | * special exception the ":" character is not allowed, as we | |
514 | * use that as field separator in $LISTEN_FDNAMES. | |
515 | * | |
516 | * Note that the empty string is explicitly allowed | |
517 | * here. However, we limit the length of the names to 255 | |
518 | * characters. */ | |
519 | ||
520 | if (!s) | |
521 | return false; | |
522 | ||
523 | for (p = s; *p; p++) { | |
524 | if (*p < ' ') | |
525 | return false; | |
526 | if (*p >= 127) | |
527 | return false; | |
528 | if (*p == ':') | |
529 | return false; | |
530 | } | |
531 | ||
ae3f4bae | 532 | return p - s <= FDNAME_MAX; |
4fee3975 | 533 | } |
4aeb20f5 LP |
534 | |
535 | int fd_get_path(int fd, char **ret) { | |
a0fe2a2d | 536 | int r; |
4aeb20f5 | 537 | |
46693a79 YW |
538 | assert(fd >= 0 || fd == AT_FDCWD); |
539 | ||
540 | if (fd == AT_FDCWD) | |
541 | return safe_getcwd(ret); | |
542 | ||
ddb6eeaf | 543 | r = readlink_malloc(FORMAT_PROC_FD_PATH(fd), ret); |
f267719c LP |
544 | if (r == -ENOENT) { |
545 | /* ENOENT can mean two things: that the fd does not exist or that /proc is not mounted. Let's make | |
5238e957 | 546 | * things debuggable and distinguish the two. */ |
4aeb20f5 | 547 | |
8fe8f3aa LP |
548 | if (proc_mounted() == 0) |
549 | return -ENOSYS; /* /proc is not available or not set up properly, we're most likely in some chroot | |
550 | * environment. */ | |
f267719c LP |
551 | return -EBADF; /* The directory exists, hence it's the fd that doesn't. */ |
552 | } | |
a0fe2a2d LP |
553 | |
554 | return r; | |
4aeb20f5 | 555 | } |
046a82c1 LP |
556 | |
557 | int move_fd(int from, int to, int cloexec) { | |
558 | int r; | |
559 | ||
560 | /* Move fd 'from' to 'to', make sure FD_CLOEXEC remains equal if requested, and release the old fd. If | |
561 | * 'cloexec' is passed as -1, the original FD_CLOEXEC is inherited for the new fd. If it is 0, it is turned | |
562 | * off, if it is > 0 it is turned on. */ | |
563 | ||
564 | if (from < 0) | |
565 | return -EBADF; | |
566 | if (to < 0) | |
567 | return -EBADF; | |
568 | ||
569 | if (from == to) { | |
570 | ||
571 | if (cloexec >= 0) { | |
572 | r = fd_cloexec(to, cloexec); | |
573 | if (r < 0) | |
574 | return r; | |
575 | } | |
576 | ||
577 | return to; | |
578 | } | |
579 | ||
580 | if (cloexec < 0) { | |
581 | int fl; | |
582 | ||
583 | fl = fcntl(from, F_GETFD, 0); | |
584 | if (fl < 0) | |
585 | return -errno; | |
586 | ||
587 | cloexec = !!(fl & FD_CLOEXEC); | |
588 | } | |
589 | ||
590 | r = dup3(from, to, cloexec ? O_CLOEXEC : 0); | |
591 | if (r < 0) | |
592 | return -errno; | |
593 | ||
594 | assert(r == to); | |
595 | ||
596 | safe_close(from); | |
597 | ||
598 | return to; | |
599 | } | |
a548e14d | 600 | |
7fe2903c LP |
601 | int fd_move_above_stdio(int fd) { |
602 | int flags, copy; | |
603 | PROTECT_ERRNO; | |
604 | ||
605 | /* Moves the specified file descriptor if possible out of the range [0…2], i.e. the range of | |
606 | * stdin/stdout/stderr. If it can't be moved outside of this range the original file descriptor is | |
607 | * returned. This call is supposed to be used for long-lasting file descriptors we allocate in our code that | |
608 | * might get loaded into foreign code, and where we want ensure our fds are unlikely used accidentally as | |
609 | * stdin/stdout/stderr of unrelated code. | |
610 | * | |
611 | * Note that this doesn't fix any real bugs, it just makes it less likely that our code will be affected by | |
612 | * buggy code from others that mindlessly invokes 'fprintf(stderr, …' or similar in places where stderr has | |
613 | * been closed before. | |
614 | * | |
615 | * This function is written in a "best-effort" and "least-impact" style. This means whenever we encounter an | |
616 | * error we simply return the original file descriptor, and we do not touch errno. */ | |
617 | ||
618 | if (fd < 0 || fd > 2) | |
619 | return fd; | |
620 | ||
621 | flags = fcntl(fd, F_GETFD, 0); | |
622 | if (flags < 0) | |
623 | return fd; | |
624 | ||
625 | if (flags & FD_CLOEXEC) | |
626 | copy = fcntl(fd, F_DUPFD_CLOEXEC, 3); | |
627 | else | |
628 | copy = fcntl(fd, F_DUPFD, 3); | |
629 | if (copy < 0) | |
630 | return fd; | |
631 | ||
632 | assert(copy > 2); | |
633 | ||
634 | (void) close(fd); | |
635 | return copy; | |
636 | } | |
aa11e28b LP |
637 | |
638 | int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd) { | |
351293b3 ZJS |
639 | int fd[3] = { original_input_fd, /* Put together an array of fds we work on */ |
640 | original_output_fd, | |
641 | original_error_fd }, | |
642 | null_fd = -EBADF, /* If we open /dev/null, we store the fd to it here */ | |
643 | copy_fd[3] = { -EBADF, -EBADF, -EBADF }, /* This contains all fds we duplicate here | |
644 | * temporarily, and hence need to close at the end. */ | |
645 | r; | |
aa11e28b LP |
646 | bool null_readable, null_writable; |
647 | ||
254d1313 ZJS |
648 | /* Sets up stdin, stdout, stderr with the three file descriptors passed in. If any of the descriptors |
649 | * is specified as -EBADF it will be connected with /dev/null instead. If any of the file descriptors | |
650 | * is passed as itself (e.g. stdin as STDIN_FILENO) it is left unmodified, but the O_CLOEXEC bit is | |
651 | * turned off should it be on. | |
aa11e28b | 652 | * |
254d1313 ZJS |
653 | * Note that if any of the passed file descriptors are > 2 they will be closed — both on success and |
654 | * on failure! Thus, callers should assume that when this function returns the input fds are | |
655 | * invalidated. | |
aa11e28b LP |
656 | * |
657 | * Note that when this function fails stdin/stdout/stderr might remain half set up! | |
658 | * | |
659 | * O_CLOEXEC is turned off for all three file descriptors (which is how it should be for | |
660 | * stdin/stdout/stderr). */ | |
661 | ||
662 | null_readable = original_input_fd < 0; | |
663 | null_writable = original_output_fd < 0 || original_error_fd < 0; | |
664 | ||
665 | /* First step, open /dev/null once, if we need it */ | |
666 | if (null_readable || null_writable) { | |
667 | ||
668 | /* Let's open this with O_CLOEXEC first, and convert it to non-O_CLOEXEC when we move the fd to the final position. */ | |
669 | null_fd = open("/dev/null", (null_readable && null_writable ? O_RDWR : | |
670 | null_readable ? O_RDONLY : O_WRONLY) | O_CLOEXEC); | |
671 | if (null_fd < 0) { | |
672 | r = -errno; | |
673 | goto finish; | |
674 | } | |
675 | ||
676 | /* If this fd is in the 0…2 range, let's move it out of it */ | |
677 | if (null_fd < 3) { | |
678 | int copy; | |
679 | ||
680 | copy = fcntl(null_fd, F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */ | |
681 | if (copy < 0) { | |
682 | r = -errno; | |
683 | goto finish; | |
684 | } | |
685 | ||
ee3455cf | 686 | close_and_replace(null_fd, copy); |
aa11e28b LP |
687 | } |
688 | } | |
689 | ||
690 | /* Let's assemble fd[] with the fds to install in place of stdin/stdout/stderr */ | |
351293b3 | 691 | for (int i = 0; i < 3; i++) { |
aa11e28b LP |
692 | |
693 | if (fd[i] < 0) | |
694 | fd[i] = null_fd; /* A negative parameter means: connect this one to /dev/null */ | |
695 | else if (fd[i] != i && fd[i] < 3) { | |
696 | /* This fd is in the 0…2 territory, but not at its intended place, move it out of there, so that we can work there. */ | |
697 | copy_fd[i] = fcntl(fd[i], F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */ | |
698 | if (copy_fd[i] < 0) { | |
699 | r = -errno; | |
700 | goto finish; | |
701 | } | |
702 | ||
703 | fd[i] = copy_fd[i]; | |
704 | } | |
705 | } | |
706 | ||
254d1313 ZJS |
707 | /* At this point we now have the fds to use in fd[], and they are all above the stdio range, so that |
708 | * we have freedom to move them around. If the fds already were at the right places then the specific | |
709 | * fds are -EBADF. Let's now move them to the right places. This is the point of no return. */ | |
351293b3 | 710 | for (int i = 0; i < 3; i++) { |
aa11e28b LP |
711 | |
712 | if (fd[i] == i) { | |
713 | ||
714 | /* fd is already in place, but let's make sure O_CLOEXEC is off */ | |
715 | r = fd_cloexec(i, false); | |
716 | if (r < 0) | |
717 | goto finish; | |
718 | ||
719 | } else { | |
720 | assert(fd[i] > 2); | |
721 | ||
722 | if (dup2(fd[i], i) < 0) { /* Turns off O_CLOEXEC on the new fd. */ | |
723 | r = -errno; | |
724 | goto finish; | |
725 | } | |
726 | } | |
727 | } | |
728 | ||
729 | r = 0; | |
730 | ||
731 | finish: | |
732 | /* Close the original fds, but only if they were outside of the stdio range. Also, properly check for the same | |
733 | * fd passed in multiple times. */ | |
734 | safe_close_above_stdio(original_input_fd); | |
735 | if (original_output_fd != original_input_fd) | |
736 | safe_close_above_stdio(original_output_fd); | |
737 | if (original_error_fd != original_input_fd && original_error_fd != original_output_fd) | |
738 | safe_close_above_stdio(original_error_fd); | |
739 | ||
740 | /* Close the copies we moved > 2 */ | |
351293b3 | 741 | for (int i = 0; i < 3; i++) |
aa11e28b LP |
742 | safe_close(copy_fd[i]); |
743 | ||
744 | /* Close our null fd, if it's > 2 */ | |
745 | safe_close_above_stdio(null_fd); | |
746 | ||
747 | return r; | |
748 | } | |
f2324783 LP |
749 | |
750 | int fd_reopen(int fd, int flags) { | |
d6274e6b | 751 | int new_fd, r; |
f2324783 | 752 | |
42db4a8d LP |
753 | assert(fd >= 0 || fd == AT_FDCWD); |
754 | ||
f2324783 LP |
755 | /* Reopens the specified fd with new flags. This is useful for convert an O_PATH fd into a regular one, or to |
756 | * turn O_RDWR fds into O_RDONLY fds. | |
757 | * | |
758 | * This doesn't work on sockets (since they cannot be open()ed, ever). | |
759 | * | |
42db4a8d LP |
760 | * This implicitly resets the file read index to 0. |
761 | * | |
fdb583e6 LP |
762 | * If AT_FDCWD is specified as file descriptor gets an fd to the current cwd. |
763 | * | |
764 | * If the specified file descriptor refers to a symlink via O_PATH, then this function cannot be used | |
765 | * to follow that symlink. Because we cannot have non-O_PATH fds to symlinks reopening it without | |
766 | * O_PATH will always result in -ELOOP. Or in other words: if you have an O_PATH fd to a symlink you | |
767 | * can reopen it only if you pass O_PATH again. */ | |
768 | ||
769 | if (FLAGS_SET(flags, O_NOFOLLOW)) | |
770 | /* O_NOFOLLOW is not allowed in fd_reopen(), because after all this is primarily implemented | |
771 | * via a symlink-based interface in /proc/self/fd. Let's refuse this here early. Note that | |
772 | * the kernel would generate ELOOP here too, hence this manual check is mostly redundant – | |
773 | * the only reason we add it here is so that the O_DIRECTORY special case (see below) behaves | |
774 | * the same way as the non-O_DIRECTORY case. */ | |
775 | return -ELOOP; | |
f2324783 | 776 | |
42db4a8d | 777 | if (FLAGS_SET(flags, O_DIRECTORY) || fd == AT_FDCWD) { |
b4f73d1e LP |
778 | /* If we shall reopen the fd as directory we can just go via "." and thus bypass the whole |
779 | * magic /proc/ directory, and make ourselves independent of that being mounted. */ | |
42db4a8d | 780 | new_fd = openat(fd, ".", flags | O_DIRECTORY); |
b4f73d1e LP |
781 | if (new_fd < 0) |
782 | return -errno; | |
783 | ||
784 | return new_fd; | |
785 | } | |
786 | ||
42db4a8d LP |
787 | assert(fd >= 0); |
788 | ||
ddb6eeaf | 789 | new_fd = open(FORMAT_PROC_FD_PATH(fd), flags); |
f8606626 LP |
790 | if (new_fd < 0) { |
791 | if (errno != ENOENT) | |
792 | return -errno; | |
793 | ||
d6274e6b LP |
794 | r = proc_mounted(); |
795 | if (r == 0) | |
f8606626 LP |
796 | return -ENOSYS; /* if we have no /proc/, the concept is not implementable */ |
797 | ||
d6274e6b LP |
798 | return r > 0 ? -EBADF : -ENOENT; /* If /proc/ is definitely around then this means the fd is |
799 | * not valid, otherwise let's propagate the original | |
800 | * error */ | |
f8606626 | 801 | } |
f2324783 LP |
802 | |
803 | return new_fd; | |
804 | } | |
9264cc39 | 805 | |
5f5865f0 LP |
806 | int fd_reopen_condition( |
807 | int fd, | |
808 | int flags, | |
809 | int mask, | |
810 | int *ret_new_fd) { | |
811 | ||
812 | int r, new_fd; | |
813 | ||
814 | assert(fd >= 0); | |
815 | ||
816 | /* Invokes fd_reopen(fd, flags), but only if the existing F_GETFL flags don't match the specified | |
817 | * flags (masked by the specified mask). This is useful for converting O_PATH fds into real fds if | |
818 | * needed, but only then. */ | |
819 | ||
820 | r = fcntl(fd, F_GETFL); | |
821 | if (r < 0) | |
822 | return -errno; | |
823 | ||
824 | if ((r & mask) == (flags & mask)) { | |
254d1313 | 825 | *ret_new_fd = -EBADF; |
5f5865f0 LP |
826 | return fd; |
827 | } | |
828 | ||
829 | new_fd = fd_reopen(fd, flags); | |
830 | if (new_fd < 0) | |
831 | return new_fd; | |
832 | ||
833 | *ret_new_fd = new_fd; | |
834 | return new_fd; | |
835 | } | |
836 | ||
ea61e2e9 YW |
837 | int fd_is_opath(int fd) { |
838 | int r; | |
839 | ||
840 | assert(fd >= 0); | |
841 | ||
842 | r = fcntl(fd, F_GETFL); | |
843 | if (r < 0) | |
844 | return -errno; | |
845 | ||
846 | return FLAGS_SET(r, O_PATH); | |
847 | } | |
848 | ||
9264cc39 LP |
849 | int read_nr_open(void) { |
850 | _cleanup_free_ char *nr_open = NULL; | |
851 | int r; | |
852 | ||
853 | /* Returns the kernel's current fd limit, either by reading it of /proc/sys if that works, or using the | |
854 | * hard-coded default compiled-in value of current kernels (1M) if not. This call will never fail. */ | |
855 | ||
856 | r = read_one_line_file("/proc/sys/fs/nr_open", &nr_open); | |
857 | if (r < 0) | |
858 | log_debug_errno(r, "Failed to read /proc/sys/fs/nr_open, ignoring: %m"); | |
859 | else { | |
860 | int v; | |
861 | ||
862 | r = safe_atoi(nr_open, &v); | |
863 | if (r < 0) | |
864 | log_debug_errno(r, "Failed to parse /proc/sys/fs/nr_open value '%s', ignoring: %m", nr_open); | |
865 | else | |
866 | return v; | |
867 | } | |
868 | ||
2aed63f4 | 869 | /* If we fail, fall back to the hard-coded kernel limit of 1024 * 1024. */ |
9264cc39 LP |
870 | return 1024 * 1024; |
871 | } | |
65ddc2c5 | 872 | |
7e93a658 YW |
873 | int fd_get_diskseq(int fd, uint64_t *ret) { |
874 | uint64_t diskseq; | |
875 | ||
876 | assert(fd >= 0); | |
877 | assert(ret); | |
878 | ||
879 | if (ioctl(fd, BLKGETDISKSEQ, &diskseq) < 0) { | |
880 | /* Note that the kernel is weird: non-existing ioctls currently return EINVAL | |
881 | * rather than ENOTTY on loopback block devices. They should fix that in the kernel, | |
882 | * but in the meantime we accept both here. */ | |
883 | if (!ERRNO_IS_NOT_SUPPORTED(errno) && errno != EINVAL) | |
884 | return -errno; | |
885 | ||
886 | return -EOPNOTSUPP; | |
887 | } | |
888 | ||
889 | *ret = diskseq; | |
890 | ||
891 | return 0; | |
892 | } | |
af423b4b DDM |
893 | |
894 | int dir_fd_is_root(int dir_fd) { | |
895 | STRUCT_NEW_STATX_DEFINE(st); | |
896 | STRUCT_NEW_STATX_DEFINE(pst); | |
897 | int r; | |
898 | ||
899 | assert(dir_fd >= 0); | |
900 | ||
901 | r = statx_fallback(dir_fd, ".", 0, STATX_TYPE|STATX_INO|STATX_MNT_ID, &st.sx); | |
902 | if (r == -ENOTDIR) | |
903 | return false; | |
904 | if (r < 0) | |
905 | return r; | |
906 | ||
b4cb4c5c YW |
907 | r = statx_fallback(dir_fd, "..", 0, STATX_TYPE|STATX_INO|STATX_MNT_ID, &pst.sx); |
908 | if (r < 0) | |
909 | return r; | |
910 | ||
911 | /* First, compare inode. If these are different, the fd does not point to the root directory "/". */ | |
912 | if (!statx_inode_same(&st.sx, &pst.sx)) | |
913 | return false; | |
914 | ||
8d3c49b1 YW |
915 | /* Even if the parent directory has the same inode, the fd may not point to the root directory "/", |
916 | * and we also need to check that the mount ids are the same. Otherwise, a construct like the | |
917 | * following could be used to trick us: | |
918 | * | |
919 | * $ mkdir /tmp/x /tmp/x/y | |
920 | * $ mount --bind /tmp/x /tmp/x/y | |
921 | * | |
922 | * Note, statx() does not provide the mount ID and path_get_mnt_id_at() does not work when an old | |
923 | * kernel is used without /proc mounted. In that case, let's assume that we do not have such spurious | |
924 | * mount points in an early boot stage, and silently skip the following check. */ | |
925 | ||
af423b4b DDM |
926 | if (!FLAGS_SET(st.nsx.stx_mask, STATX_MNT_ID)) { |
927 | int mntid; | |
928 | ||
929 | r = path_get_mnt_id_at(dir_fd, "", &mntid); | |
8d3c49b1 YW |
930 | if (r == -ENOSYS) |
931 | return true; /* skip the mount ID check */ | |
af423b4b DDM |
932 | if (r < 0) |
933 | return r; | |
934 | assert(mntid >= 0); | |
935 | ||
936 | st.nsx.stx_mnt_id = mntid; | |
937 | st.nsx.stx_mask |= STATX_MNT_ID; | |
938 | } | |
939 | ||
af423b4b DDM |
940 | if (!FLAGS_SET(pst.nsx.stx_mask, STATX_MNT_ID)) { |
941 | int mntid; | |
942 | ||
943 | r = path_get_mnt_id_at(dir_fd, "..", &mntid); | |
8d3c49b1 YW |
944 | if (r == -ENOSYS) |
945 | return true; /* skip the mount ID check */ | |
af423b4b DDM |
946 | if (r < 0) |
947 | return r; | |
948 | assert(mntid >= 0); | |
949 | ||
950 | pst.nsx.stx_mnt_id = mntid; | |
951 | pst.nsx.stx_mask |= STATX_MNT_ID; | |
952 | } | |
953 | ||
b4cb4c5c | 954 | return statx_mount_same(&st.nsx, &pst.nsx); |
af423b4b | 955 | } |
b2b84f4b LP |
956 | |
957 | const char *accmode_to_string(int flags) { | |
958 | switch (flags & O_ACCMODE) { | |
959 | case O_RDONLY: | |
960 | return "ro"; | |
961 | case O_WRONLY: | |
962 | return "wo"; | |
963 | case O_RDWR: | |
964 | return "rw"; | |
965 | default: | |
966 | return NULL; | |
967 | } | |
968 | } |