]>
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> | |
65ddc2c5 ZJS |
5 | #include <linux/btrfs.h> |
6 | #include <linux/magic.h> | |
7 | #include <sys/ioctl.h> | |
11c3a366 | 8 | #include <sys/resource.h> |
11c3a366 TA |
9 | #include <sys/stat.h> |
10 | #include <unistd.h> | |
11 | ||
4960ce43 | 12 | #include "alloc-util.h" |
8fb3f009 | 13 | #include "dirent-util.h" |
3ffd4af2 | 14 | #include "fd-util.h" |
a548e14d | 15 | #include "fileio.h" |
4aeb20f5 | 16 | #include "fs-util.h" |
4960ce43 | 17 | #include "io-util.h" |
11c3a366 | 18 | #include "macro.h" |
0499585f | 19 | #include "missing_fcntl.h" |
f5947a5e | 20 | #include "missing_syscall.h" |
93cc7779 | 21 | #include "parse-util.h" |
11c3a366 | 22 | #include "path-util.h" |
df0ff127 | 23 | #include "process-util.h" |
93cc7779 | 24 | #include "socket-util.h" |
b8cfa2da | 25 | #include "sort-util.h" |
f8606626 | 26 | #include "stat-util.h" |
4aeb20f5 | 27 | #include "stdio-util.h" |
e4de7287 | 28 | #include "tmpfile-util.h" |
f8606626 | 29 | #include "util.h" |
3ffd4af2 | 30 | |
6a461d1f ZJS |
31 | /* The maximum number of iterations in the loop to close descriptors in the fallback case |
32 | * when /proc/self/fd/ is inaccessible. */ | |
33 | #define MAX_FD_LOOP_LIMIT (1024*1024) | |
34 | ||
3ffd4af2 LP |
35 | int 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 | ||
56 | int 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 | ||
3042bbeb | 80 | void safe_close_pair(int p[static 2]) { |
3ffd4af2 LP |
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 | ||
da6053d0 | 94 | void close_many(const int fds[], size_t n_fd) { |
3ffd4af2 LP |
95 | assert(fds || n_fd <= 0); |
96 | ||
fe96c0f8 | 97 | for (size_t i = 0; i < n_fd; i++) |
3ffd4af2 LP |
98 | safe_close(fds[i]); |
99 | } | |
100 | ||
101 | int fclose_nointr(FILE *f) { | |
102 | assert(f); | |
103 | ||
104 | /* Same as close_nointr(), but for fclose() */ | |
105 | ||
75f6d5d8 LP |
106 | errno = 0; /* Extra safety: if the FILE* object is not encapsulating an fd, it might not set errno |
107 | * correctly. Let's hence initialize it to zero first, so that we aren't confused by any | |
108 | * prior errno here */ | |
3ffd4af2 LP |
109 | if (fclose(f) == 0) |
110 | return 0; | |
111 | ||
112 | if (errno == EINTR) | |
113 | return 0; | |
114 | ||
75f6d5d8 | 115 | return errno_or_else(EIO); |
3ffd4af2 LP |
116 | } |
117 | ||
118 | FILE* safe_fclose(FILE *f) { | |
119 | ||
120 | /* Same as safe_close(), but for fclose() */ | |
121 | ||
122 | if (f) { | |
123 | PROTECT_ERRNO; | |
124 | ||
6dce3bb4 | 125 | assert_se(fclose_nointr(f) != -EBADF); |
3ffd4af2 LP |
126 | } |
127 | ||
128 | return NULL; | |
129 | } | |
130 | ||
131 | DIR* safe_closedir(DIR *d) { | |
132 | ||
133 | if (d) { | |
134 | PROTECT_ERRNO; | |
135 | ||
136 | assert_se(closedir(d) >= 0 || errno != EBADF); | |
137 | } | |
138 | ||
139 | return NULL; | |
140 | } | |
141 | ||
142 | int fd_nonblock(int fd, bool nonblock) { | |
143 | int flags, nflags; | |
144 | ||
145 | assert(fd >= 0); | |
146 | ||
147 | flags = fcntl(fd, F_GETFL, 0); | |
148 | if (flags < 0) | |
149 | return -errno; | |
150 | ||
0da96503 | 151 | nflags = UPDATE_FLAG(flags, O_NONBLOCK, nonblock); |
3ffd4af2 LP |
152 | if (nflags == flags) |
153 | return 0; | |
154 | ||
155 | if (fcntl(fd, F_SETFL, nflags) < 0) | |
156 | return -errno; | |
157 | ||
158 | return 0; | |
159 | } | |
160 | ||
161 | int fd_cloexec(int fd, bool cloexec) { | |
162 | int flags, nflags; | |
163 | ||
164 | assert(fd >= 0); | |
165 | ||
166 | flags = fcntl(fd, F_GETFD, 0); | |
167 | if (flags < 0) | |
168 | return -errno; | |
169 | ||
0da96503 | 170 | nflags = UPDATE_FLAG(flags, FD_CLOEXEC, cloexec); |
3ffd4af2 LP |
171 | if (nflags == flags) |
172 | return 0; | |
173 | ||
174 | if (fcntl(fd, F_SETFD, nflags) < 0) | |
175 | return -errno; | |
176 | ||
177 | return 0; | |
178 | } | |
179 | ||
da6053d0 | 180 | _pure_ static bool fd_in_set(int fd, const int fdset[], size_t n_fdset) { |
3ffd4af2 LP |
181 | assert(n_fdset == 0 || fdset); |
182 | ||
fe96c0f8 | 183 | for (size_t i = 0; i < n_fdset; i++) |
3ffd4af2 LP |
184 | if (fdset[i] == fd) |
185 | return true; | |
186 | ||
187 | return false; | |
188 | } | |
189 | ||
498e265d LP |
190 | static int get_max_fd(void) { |
191 | struct rlimit rl; | |
192 | rlim_t m; | |
193 | ||
194 | /* Return the highest possible fd, based RLIMIT_NOFILE, but enforcing FD_SETSIZE-1 as lower boundary | |
195 | * and INT_MAX as upper boundary. */ | |
196 | ||
197 | if (getrlimit(RLIMIT_NOFILE, &rl) < 0) | |
198 | return -errno; | |
199 | ||
200 | m = MAX(rl.rlim_cur, rl.rlim_max); | |
201 | if (m < FD_SETSIZE) /* Let's always cover at least 1024 fds */ | |
202 | return FD_SETSIZE-1; | |
203 | ||
204 | if (m == RLIM_INFINITY || m > INT_MAX) /* Saturate on overflow. After all fds are "int", hence can | |
205 | * never be above INT_MAX */ | |
206 | return INT_MAX; | |
207 | ||
208 | return (int) (m - 1); | |
209 | } | |
210 | ||
e7e7c07c | 211 | int close_all_fds(int except[], size_t n_except) { |
b8cfa2da | 212 | static bool have_close_range = true; /* Assume we live in the future */ |
3ffd4af2 | 213 | _cleanup_closedir_ DIR *d = NULL; |
3ffd4af2 LP |
214 | int r = 0; |
215 | ||
216 | assert(n_except == 0 || except); | |
217 | ||
b8cfa2da LP |
218 | if (have_close_range) { |
219 | /* In the best case we have close_range() to close all fds between a start and an end fd, | |
220 | * which we can use on the "inverted" exception array, i.e. all intervals between all | |
221 | * adjacent pairs from the sorted exception array. This changes loop complexity from O(n) | |
222 | * where n is number of open fds to O(m⋅log(m)) where m is the number of fds to keep | |
223 | * open. Given that we assume n ≫ m that's preferable to us. */ | |
224 | ||
225 | if (n_except == 0) { | |
226 | /* Close everything. Yay! */ | |
227 | ||
228 | if (close_range(3, -1, 0) >= 0) | |
9c46228b | 229 | return 0; |
b8cfa2da | 230 | |
9c46228b ZJS |
231 | if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) |
232 | have_close_range = false; | |
233 | else | |
b8cfa2da LP |
234 | return -errno; |
235 | ||
b8cfa2da | 236 | } else { |
9c46228b | 237 | typesafe_qsort(except, n_except, cmp_int); |
b8cfa2da | 238 | |
9c46228b ZJS |
239 | for (size_t i = 0; i < n_except; i++) { |
240 | int start = i == 0 ? 2 : MAX(except[i-1], 2); /* The first three fds shall always remain open */ | |
241 | int end = MAX(except[i], 2); | |
b8cfa2da | 242 | |
9c46228b | 243 | assert(end >= start); |
b8cfa2da | 244 | |
9c46228b ZJS |
245 | if (end - start <= 1) |
246 | continue; | |
b8cfa2da | 247 | |
9c46228b ZJS |
248 | /* Close everything between the start and end fds (both of which shall stay open) */ |
249 | if (close_range(start + 1, end - 1, 0) < 0) { | |
250 | if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) | |
b8cfa2da | 251 | have_close_range = false; |
9c46228b ZJS |
252 | else |
253 | return -errno; | |
254 | goto opendir_fallback; | |
b8cfa2da | 255 | } |
9c46228b | 256 | } |
b8cfa2da | 257 | |
9c46228b | 258 | /* The loop succeeded. Let's now close everything beyond the end */ |
b8cfa2da | 259 | |
9c46228b ZJS |
260 | if (except[n_except-1] >= INT_MAX) /* Don't let the addition below overflow */ |
261 | return 0; | |
b8cfa2da | 262 | |
9c46228b | 263 | int start = MAX(except[n_except-1], 2); |
b8cfa2da | 264 | |
9c46228b ZJS |
265 | if (close_range(start + 1, -1, 0) >= 0) |
266 | return 0; | |
b8cfa2da | 267 | |
9c46228b ZJS |
268 | if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) |
269 | have_close_range = false; | |
270 | else | |
271 | return -errno; | |
b8cfa2da | 272 | } |
b8cfa2da LP |
273 | } |
274 | ||
9c46228b ZJS |
275 | /* Fallback for when close_range() is not supported */ |
276 | opendir_fallback: | |
e7e7c07c | 277 | d = opendir("/proc/self/fd"); |
9c46228b ZJS |
278 | if (d) { |
279 | struct dirent *de; | |
3ffd4af2 | 280 | |
9c46228b ZJS |
281 | FOREACH_DIRENT(de, d, return -errno) { |
282 | int fd = -1, q; | |
37bc14de | 283 | |
9c46228b ZJS |
284 | if (safe_atoi(de->d_name, &fd) < 0) |
285 | /* Let's better ignore this, just in case */ | |
286 | continue; | |
37bc14de | 287 | |
9c46228b ZJS |
288 | if (fd < 3) |
289 | continue; | |
6a461d1f | 290 | |
9c46228b ZJS |
291 | if (fd == dirfd(d)) |
292 | continue; | |
3ffd4af2 LP |
293 | |
294 | if (fd_in_set(fd, except, n_except)) | |
295 | continue; | |
296 | ||
e43bc9f5 | 297 | q = close_nointr(fd); |
9c46228b | 298 | if (q < 0 && q != -EBADF && r >= 0) /* Valgrind has its own FD and doesn't want to have it closed */ |
e43bc9f5 | 299 | r = q; |
3ffd4af2 LP |
300 | } |
301 | ||
302 | return r; | |
303 | } | |
304 | ||
e7e7c07c LP |
305 | /* Fallback for when /proc isn't available (for example in chroots) by brute-forcing through the file |
306 | * descriptor table. */ | |
3ffd4af2 | 307 | |
9c46228b ZJS |
308 | int max_fd = get_max_fd(); |
309 | if (max_fd < 0) | |
310 | return max_fd; | |
3ffd4af2 | 311 | |
9c46228b ZJS |
312 | /* Refuse to do the loop over more too many elements. It's better to fail immediately than to |
313 | * spin the CPU for a long time. */ | |
314 | if (max_fd > MAX_FD_LOOP_LIMIT) | |
315 | return log_debug_errno(SYNTHETIC_ERRNO(EPERM), | |
316 | "/proc/self/fd is inaccessible. Refusing to loop over %d potential fds.", | |
317 | max_fd); | |
3ffd4af2 | 318 | |
9c46228b ZJS |
319 | for (int fd = 3; fd >= 0; fd = fd < max_fd ? fd + 1 : -1) { |
320 | int q; | |
3ffd4af2 LP |
321 | |
322 | if (fd_in_set(fd, except, n_except)) | |
323 | continue; | |
324 | ||
e43bc9f5 | 325 | q = close_nointr(fd); |
9c46228b | 326 | if (q < 0 && q != -EBADF && r >= 0) |
e43bc9f5 | 327 | r = q; |
3ffd4af2 LP |
328 | } |
329 | ||
330 | return r; | |
331 | } | |
332 | ||
333 | int same_fd(int a, int b) { | |
334 | struct stat sta, stb; | |
335 | pid_t pid; | |
336 | int r, fa, fb; | |
337 | ||
338 | assert(a >= 0); | |
339 | assert(b >= 0); | |
340 | ||
341 | /* Compares two file descriptors. Note that semantics are | |
342 | * quite different depending on whether we have kcmp() or we | |
343 | * don't. If we have kcmp() this will only return true for | |
344 | * dup()ed file descriptors, but not otherwise. If we don't | |
345 | * have kcmp() this will also return true for two fds of the same | |
346 | * file, created by separate open() calls. Since we use this | |
347 | * call mostly for filtering out duplicates in the fd store | |
348 | * this difference hopefully doesn't matter too much. */ | |
349 | ||
350 | if (a == b) | |
351 | return true; | |
352 | ||
353 | /* Try to use kcmp() if we have it. */ | |
df0ff127 | 354 | pid = getpid_cached(); |
3ffd4af2 LP |
355 | r = kcmp(pid, pid, KCMP_FILE, a, b); |
356 | if (r == 0) | |
357 | return true; | |
358 | if (r > 0) | |
359 | return false; | |
9e2acd1d | 360 | if (!IN_SET(errno, ENOSYS, EACCES, EPERM)) |
3ffd4af2 LP |
361 | return -errno; |
362 | ||
363 | /* We don't have kcmp(), use fstat() instead. */ | |
364 | if (fstat(a, &sta) < 0) | |
365 | return -errno; | |
366 | ||
367 | if (fstat(b, &stb) < 0) | |
368 | return -errno; | |
369 | ||
370 | if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT)) | |
371 | return false; | |
372 | ||
373 | /* We consider all device fds different, since two device fds | |
374 | * might refer to quite different device contexts even though | |
375 | * they share the same inode and backing dev_t. */ | |
376 | ||
377 | if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode)) | |
378 | return false; | |
379 | ||
380 | if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino) | |
381 | return false; | |
382 | ||
383 | /* The fds refer to the same inode on disk, let's also check | |
384 | * if they have the same fd flags. This is useful to | |
385 | * distinguish the read and write side of a pipe created with | |
386 | * pipe(). */ | |
387 | fa = fcntl(a, F_GETFL); | |
388 | if (fa < 0) | |
389 | return -errno; | |
390 | ||
391 | fb = fcntl(b, F_GETFL); | |
392 | if (fb < 0) | |
393 | return -errno; | |
394 | ||
395 | return fa == fb; | |
396 | } | |
397 | ||
398 | void cmsg_close_all(struct msghdr *mh) { | |
399 | struct cmsghdr *cmsg; | |
400 | ||
401 | assert(mh); | |
402 | ||
403 | CMSG_FOREACH(cmsg, mh) | |
404 | if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) | |
405 | close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int)); | |
406 | } | |
4fee3975 LP |
407 | |
408 | bool fdname_is_valid(const char *s) { | |
409 | const char *p; | |
410 | ||
411 | /* Validates a name for $LISTEN_FDNAMES. We basically allow | |
412 | * everything ASCII that's not a control character. Also, as | |
413 | * special exception the ":" character is not allowed, as we | |
414 | * use that as field separator in $LISTEN_FDNAMES. | |
415 | * | |
416 | * Note that the empty string is explicitly allowed | |
417 | * here. However, we limit the length of the names to 255 | |
418 | * characters. */ | |
419 | ||
420 | if (!s) | |
421 | return false; | |
422 | ||
423 | for (p = s; *p; p++) { | |
424 | if (*p < ' ') | |
425 | return false; | |
426 | if (*p >= 127) | |
427 | return false; | |
428 | if (*p == ':') | |
429 | return false; | |
430 | } | |
431 | ||
ae3f4bae | 432 | return p - s <= FDNAME_MAX; |
4fee3975 | 433 | } |
4aeb20f5 LP |
434 | |
435 | int fd_get_path(int fd, char **ret) { | |
a0fe2a2d | 436 | int r; |
4aeb20f5 | 437 | |
ddb6eeaf | 438 | r = readlink_malloc(FORMAT_PROC_FD_PATH(fd), ret); |
f267719c LP |
439 | if (r == -ENOENT) { |
440 | /* ENOENT can mean two things: that the fd does not exist or that /proc is not mounted. Let's make | |
5238e957 | 441 | * things debuggable and distinguish the two. */ |
4aeb20f5 | 442 | |
8fe8f3aa LP |
443 | if (proc_mounted() == 0) |
444 | return -ENOSYS; /* /proc is not available or not set up properly, we're most likely in some chroot | |
445 | * environment. */ | |
f267719c LP |
446 | return -EBADF; /* The directory exists, hence it's the fd that doesn't. */ |
447 | } | |
a0fe2a2d LP |
448 | |
449 | return r; | |
4aeb20f5 | 450 | } |
046a82c1 LP |
451 | |
452 | int move_fd(int from, int to, int cloexec) { | |
453 | int r; | |
454 | ||
455 | /* Move fd 'from' to 'to', make sure FD_CLOEXEC remains equal if requested, and release the old fd. If | |
456 | * 'cloexec' is passed as -1, the original FD_CLOEXEC is inherited for the new fd. If it is 0, it is turned | |
457 | * off, if it is > 0 it is turned on. */ | |
458 | ||
459 | if (from < 0) | |
460 | return -EBADF; | |
461 | if (to < 0) | |
462 | return -EBADF; | |
463 | ||
464 | if (from == to) { | |
465 | ||
466 | if (cloexec >= 0) { | |
467 | r = fd_cloexec(to, cloexec); | |
468 | if (r < 0) | |
469 | return r; | |
470 | } | |
471 | ||
472 | return to; | |
473 | } | |
474 | ||
475 | if (cloexec < 0) { | |
476 | int fl; | |
477 | ||
478 | fl = fcntl(from, F_GETFD, 0); | |
479 | if (fl < 0) | |
480 | return -errno; | |
481 | ||
482 | cloexec = !!(fl & FD_CLOEXEC); | |
483 | } | |
484 | ||
485 | r = dup3(from, to, cloexec ? O_CLOEXEC : 0); | |
486 | if (r < 0) | |
487 | return -errno; | |
488 | ||
489 | assert(r == to); | |
490 | ||
491 | safe_close(from); | |
492 | ||
493 | return to; | |
494 | } | |
a548e14d | 495 | |
7fe2903c LP |
496 | int fd_move_above_stdio(int fd) { |
497 | int flags, copy; | |
498 | PROTECT_ERRNO; | |
499 | ||
500 | /* Moves the specified file descriptor if possible out of the range [0…2], i.e. the range of | |
501 | * stdin/stdout/stderr. If it can't be moved outside of this range the original file descriptor is | |
502 | * returned. This call is supposed to be used for long-lasting file descriptors we allocate in our code that | |
503 | * might get loaded into foreign code, and where we want ensure our fds are unlikely used accidentally as | |
504 | * stdin/stdout/stderr of unrelated code. | |
505 | * | |
506 | * Note that this doesn't fix any real bugs, it just makes it less likely that our code will be affected by | |
507 | * buggy code from others that mindlessly invokes 'fprintf(stderr, …' or similar in places where stderr has | |
508 | * been closed before. | |
509 | * | |
510 | * This function is written in a "best-effort" and "least-impact" style. This means whenever we encounter an | |
511 | * error we simply return the original file descriptor, and we do not touch errno. */ | |
512 | ||
513 | if (fd < 0 || fd > 2) | |
514 | return fd; | |
515 | ||
516 | flags = fcntl(fd, F_GETFD, 0); | |
517 | if (flags < 0) | |
518 | return fd; | |
519 | ||
520 | if (flags & FD_CLOEXEC) | |
521 | copy = fcntl(fd, F_DUPFD_CLOEXEC, 3); | |
522 | else | |
523 | copy = fcntl(fd, F_DUPFD, 3); | |
524 | if (copy < 0) | |
525 | return fd; | |
526 | ||
527 | assert(copy > 2); | |
528 | ||
529 | (void) close(fd); | |
530 | return copy; | |
531 | } | |
aa11e28b LP |
532 | |
533 | int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd) { | |
534 | ||
535 | int fd[3] = { /* Put together an array of fds we work on */ | |
536 | original_input_fd, | |
537 | original_output_fd, | |
538 | original_error_fd | |
539 | }; | |
540 | ||
541 | int r, i, | |
542 | null_fd = -1, /* if we open /dev/null, we store the fd to it here */ | |
543 | copy_fd[3] = { -1, -1, -1 }; /* This contains all fds we duplicate here temporarily, and hence need to close at the end */ | |
544 | bool null_readable, null_writable; | |
545 | ||
546 | /* Sets up stdin, stdout, stderr with the three file descriptors passed in. If any of the descriptors is | |
547 | * specified as -1 it will be connected with /dev/null instead. If any of the file descriptors is passed as | |
548 | * itself (e.g. stdin as STDIN_FILENO) it is left unmodified, but the O_CLOEXEC bit is turned off should it be | |
549 | * on. | |
550 | * | |
551 | * Note that if any of the passed file descriptors are > 2 they will be closed — both on success and on | |
552 | * failure! Thus, callers should assume that when this function returns the input fds are invalidated. | |
553 | * | |
554 | * Note that when this function fails stdin/stdout/stderr might remain half set up! | |
555 | * | |
556 | * O_CLOEXEC is turned off for all three file descriptors (which is how it should be for | |
557 | * stdin/stdout/stderr). */ | |
558 | ||
559 | null_readable = original_input_fd < 0; | |
560 | null_writable = original_output_fd < 0 || original_error_fd < 0; | |
561 | ||
562 | /* First step, open /dev/null once, if we need it */ | |
563 | if (null_readable || null_writable) { | |
564 | ||
565 | /* Let's open this with O_CLOEXEC first, and convert it to non-O_CLOEXEC when we move the fd to the final position. */ | |
566 | null_fd = open("/dev/null", (null_readable && null_writable ? O_RDWR : | |
567 | null_readable ? O_RDONLY : O_WRONLY) | O_CLOEXEC); | |
568 | if (null_fd < 0) { | |
569 | r = -errno; | |
570 | goto finish; | |
571 | } | |
572 | ||
573 | /* If this fd is in the 0…2 range, let's move it out of it */ | |
574 | if (null_fd < 3) { | |
575 | int copy; | |
576 | ||
577 | copy = fcntl(null_fd, F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */ | |
578 | if (copy < 0) { | |
579 | r = -errno; | |
580 | goto finish; | |
581 | } | |
582 | ||
0706c012 | 583 | CLOSE_AND_REPLACE(null_fd, copy); |
aa11e28b LP |
584 | } |
585 | } | |
586 | ||
587 | /* Let's assemble fd[] with the fds to install in place of stdin/stdout/stderr */ | |
588 | for (i = 0; i < 3; i++) { | |
589 | ||
590 | if (fd[i] < 0) | |
591 | fd[i] = null_fd; /* A negative parameter means: connect this one to /dev/null */ | |
592 | else if (fd[i] != i && fd[i] < 3) { | |
593 | /* 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. */ | |
594 | copy_fd[i] = fcntl(fd[i], F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */ | |
595 | if (copy_fd[i] < 0) { | |
596 | r = -errno; | |
597 | goto finish; | |
598 | } | |
599 | ||
600 | fd[i] = copy_fd[i]; | |
601 | } | |
602 | } | |
603 | ||
604 | /* At this point we now have the fds to use in fd[], and they are all above the stdio range, so that we | |
605 | * have freedom to move them around. If the fds already were at the right places then the specific fds are | |
606 | * -1. Let's now move them to the right places. This is the point of no return. */ | |
607 | for (i = 0; i < 3; i++) { | |
608 | ||
609 | if (fd[i] == i) { | |
610 | ||
611 | /* fd is already in place, but let's make sure O_CLOEXEC is off */ | |
612 | r = fd_cloexec(i, false); | |
613 | if (r < 0) | |
614 | goto finish; | |
615 | ||
616 | } else { | |
617 | assert(fd[i] > 2); | |
618 | ||
619 | if (dup2(fd[i], i) < 0) { /* Turns off O_CLOEXEC on the new fd. */ | |
620 | r = -errno; | |
621 | goto finish; | |
622 | } | |
623 | } | |
624 | } | |
625 | ||
626 | r = 0; | |
627 | ||
628 | finish: | |
629 | /* Close the original fds, but only if they were outside of the stdio range. Also, properly check for the same | |
630 | * fd passed in multiple times. */ | |
631 | safe_close_above_stdio(original_input_fd); | |
632 | if (original_output_fd != original_input_fd) | |
633 | safe_close_above_stdio(original_output_fd); | |
634 | if (original_error_fd != original_input_fd && original_error_fd != original_output_fd) | |
635 | safe_close_above_stdio(original_error_fd); | |
636 | ||
637 | /* Close the copies we moved > 2 */ | |
638 | for (i = 0; i < 3; i++) | |
639 | safe_close(copy_fd[i]); | |
640 | ||
641 | /* Close our null fd, if it's > 2 */ | |
642 | safe_close_above_stdio(null_fd); | |
643 | ||
644 | return r; | |
645 | } | |
f2324783 LP |
646 | |
647 | int fd_reopen(int fd, int flags) { | |
d6274e6b | 648 | int new_fd, r; |
f2324783 LP |
649 | |
650 | /* Reopens the specified fd with new flags. This is useful for convert an O_PATH fd into a regular one, or to | |
651 | * turn O_RDWR fds into O_RDONLY fds. | |
652 | * | |
653 | * This doesn't work on sockets (since they cannot be open()ed, ever). | |
654 | * | |
655 | * This implicitly resets the file read index to 0. */ | |
656 | ||
b4f73d1e LP |
657 | if (FLAGS_SET(flags, O_DIRECTORY)) { |
658 | /* If we shall reopen the fd as directory we can just go via "." and thus bypass the whole | |
659 | * magic /proc/ directory, and make ourselves independent of that being mounted. */ | |
660 | new_fd = openat(fd, ".", flags); | |
661 | if (new_fd < 0) | |
662 | return -errno; | |
663 | ||
664 | return new_fd; | |
665 | } | |
666 | ||
ddb6eeaf | 667 | new_fd = open(FORMAT_PROC_FD_PATH(fd), flags); |
f8606626 LP |
668 | if (new_fd < 0) { |
669 | if (errno != ENOENT) | |
670 | return -errno; | |
671 | ||
d6274e6b LP |
672 | r = proc_mounted(); |
673 | if (r == 0) | |
f8606626 LP |
674 | return -ENOSYS; /* if we have no /proc/, the concept is not implementable */ |
675 | ||
d6274e6b LP |
676 | return r > 0 ? -EBADF : -ENOENT; /* If /proc/ is definitely around then this means the fd is |
677 | * not valid, otherwise let's propagate the original | |
678 | * error */ | |
f8606626 | 679 | } |
f2324783 LP |
680 | |
681 | return new_fd; | |
682 | } | |
9264cc39 LP |
683 | |
684 | int read_nr_open(void) { | |
685 | _cleanup_free_ char *nr_open = NULL; | |
686 | int r; | |
687 | ||
688 | /* Returns the kernel's current fd limit, either by reading it of /proc/sys if that works, or using the | |
689 | * hard-coded default compiled-in value of current kernels (1M) if not. This call will never fail. */ | |
690 | ||
691 | r = read_one_line_file("/proc/sys/fs/nr_open", &nr_open); | |
692 | if (r < 0) | |
693 | log_debug_errno(r, "Failed to read /proc/sys/fs/nr_open, ignoring: %m"); | |
694 | else { | |
695 | int v; | |
696 | ||
697 | r = safe_atoi(nr_open, &v); | |
698 | if (r < 0) | |
699 | log_debug_errno(r, "Failed to parse /proc/sys/fs/nr_open value '%s', ignoring: %m", nr_open); | |
700 | else | |
701 | return v; | |
702 | } | |
703 | ||
2aed63f4 | 704 | /* If we fail, fall back to the hard-coded kernel limit of 1024 * 1024. */ |
9264cc39 LP |
705 | return 1024 * 1024; |
706 | } | |
65ddc2c5 ZJS |
707 | |
708 | /* This is here because it's fd-related and is called from sd-journal code. Other btrfs-related utilities are | |
709 | * in src/shared, but libsystemd must not link to libsystemd-shared, see docs/ARCHITECTURE.md. */ | |
710 | int btrfs_defrag_fd(int fd) { | |
711 | int r; | |
712 | ||
713 | assert(fd >= 0); | |
714 | ||
715 | r = fd_verify_regular(fd); | |
716 | if (r < 0) | |
717 | return r; | |
718 | ||
719 | if (ioctl(fd, BTRFS_IOC_DEFRAG, NULL) < 0) | |
720 | return -errno; | |
721 | ||
722 | return 0; | |
723 | } |