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