1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <linux/btrfs.h>
6 #include <linux/fs.h>
7 #include <linux/magic.h>
8 #include <sys/ioctl.h>
9 #include <sys/resource.h>
10 #include <sys/stat.h>
11 #include <unistd.h>
12
13 #include "alloc-util.h"
14 #include "dirent-util.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "fs-util.h"
18 #include "io-util.h"
19 #include "macro.h"
20 #include "missing_fcntl.h"
21 #include "missing_fs.h"
22 #include "missing_syscall.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "process-util.h"
26 #include "socket-util.h"
27 #include "sort-util.h"
28 #include "stat-util.h"
29 #include "stdio-util.h"
30 #include "tmpfile-util.h"
31 #include "util.h"
32
33 /* The maximum number of iterations in the loop to close descriptors in the fallback case
34 * when /proc/self/fd/ is inaccessible. */
35 #define MAX_FD_LOOP_LIMIT (1024*1024)
36
close_nointr(int fd)37 int close_nointr(int fd) {
38 assert(fd >= 0);
39
40 if (close(fd) >= 0)
41 return 0;
42
43 /*
44 * Just ignore EINTR; a retry loop is the wrong thing to do on
45 * Linux.
46 *
47 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
48 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
49 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
50 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
51 */
52 if (errno == EINTR)
53 return 0;
54
55 return -errno;
56 }
57
safe_close(int fd)58 int safe_close(int fd) {
59
60 /*
61 * Like close_nointr() but cannot fail. Guarantees errno is
62 * unchanged. Is a NOP with negative fds passed, and returns
63 * -1, so that it can be used in this syntax:
64 *
65 * fd = safe_close(fd);
66 */
67
68 if (fd >= 0) {
69 PROTECT_ERRNO;
70
71 /* The kernel might return pretty much any error code
72 * via close(), but the fd will be closed anyway. The
73 * only condition we want to check for here is whether
74 * the fd was invalid at all... */
75
76 assert_se(close_nointr(fd) != -EBADF);
77 }
78
79 return -1;
80 }
81
safe_close_pair(int p[static2])82 void safe_close_pair(int p[static 2]) {
83 assert(p);
84
85 if (p[0] == p[1]) {
86 /* Special case pairs which use the same fd in both
87 * directions... */
88 p[0] = p[1] = safe_close(p[0]);
89 return;
90 }
91
92 p[0] = safe_close(p[0]);
93 p[1] = safe_close(p[1]);
94 }
95
close_many(const int fds[],size_t n_fd)96 void close_many(const int fds[], size_t n_fd) {
97 assert(fds || n_fd <= 0);
98
99 for (size_t i = 0; i < n_fd; i++)
100 safe_close(fds[i]);
101 }
102
fclose_nointr(FILE * f)103 int fclose_nointr(FILE *f) {
104 assert(f);
105
106 /* Same as close_nointr(), but for fclose() */
107
108 errno = 0; /* Extra safety: if the FILE* object is not encapsulating an fd, it might not set errno
109 * correctly. Let's hence initialize it to zero first, so that we aren't confused by any
110 * prior errno here */
111 if (fclose(f) == 0)
112 return 0;
113
114 if (errno == EINTR)
115 return 0;
116
117 return errno_or_else(EIO);
118 }
119
safe_fclose(FILE * f)120 FILE* safe_fclose(FILE *f) {
121
122 /* Same as safe_close(), but for fclose() */
123
124 if (f) {
125 PROTECT_ERRNO;
126
127 assert_se(fclose_nointr(f) != -EBADF);
128 }
129
130 return NULL;
131 }
132
safe_closedir(DIR * d)133 DIR* safe_closedir(DIR *d) {
134
135 if (d) {
136 PROTECT_ERRNO;
137
138 assert_se(closedir(d) >= 0 || errno != EBADF);
139 }
140
141 return NULL;
142 }
143
fd_nonblock(int fd,bool nonblock)144 int fd_nonblock(int fd, bool nonblock) {
145 int flags, nflags;
146
147 assert(fd >= 0);
148
149 flags = fcntl(fd, F_GETFL, 0);
150 if (flags < 0)
151 return -errno;
152
153 nflags = UPDATE_FLAG(flags, O_NONBLOCK, nonblock);
154 if (nflags == flags)
155 return 0;
156
157 return RET_NERRNO(fcntl(fd, F_SETFL, nflags));
158 }
159
fd_cloexec(int fd,bool cloexec)160 int fd_cloexec(int fd, bool cloexec) {
161 int flags, nflags;
162
163 assert(fd >= 0);
164
165 flags = fcntl(fd, F_GETFD, 0);
166 if (flags < 0)
167 return -errno;
168
169 nflags = UPDATE_FLAG(flags, FD_CLOEXEC, cloexec);
170 if (nflags == flags)
171 return 0;
172
173 return RET_NERRNO(fcntl(fd, F_SETFD, nflags));
174 }
175
fd_in_set(int fd,const int fdset[],size_t n_fdset)176 _pure_ static bool fd_in_set(int fd, const int fdset[], size_t n_fdset) {
177 assert(n_fdset == 0 || fdset);
178
179 for (size_t i = 0; i < n_fdset; i++)
180 if (fdset[i] == fd)
181 return true;
182
183 return false;
184 }
185
get_max_fd(void)186 int get_max_fd(void) {
187 struct rlimit rl;
188 rlim_t m;
189
190 /* Return the highest possible fd, based RLIMIT_NOFILE, but enforcing FD_SETSIZE-1 as lower boundary
191 * and INT_MAX as upper boundary. */
192
193 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
194 return -errno;
195
196 m = MAX(rl.rlim_cur, rl.rlim_max);
197 if (m < FD_SETSIZE) /* Let's always cover at least 1024 fds */
198 return FD_SETSIZE-1;
199
200 if (m == RLIM_INFINITY || m > INT_MAX) /* Saturate on overflow. After all fds are "int", hence can
201 * never be above INT_MAX */
202 return INT_MAX;
203
204 return (int) (m - 1);
205 }
206
close_all_fds_frugal(const int except[],size_t n_except)207 static int close_all_fds_frugal(const int except[], size_t n_except) {
208 int max_fd, r = 0;
209
210 assert(n_except == 0 || except);
211
212 /* This is the inner fallback core of close_all_fds(). This never calls malloc() or opendir() or so
213 * and hence is safe to be called in signal handler context. Most users should call close_all_fds(),
214 * but when we assume we are called from signal handler context, then use this simpler call
215 * instead. */
216
217 max_fd = get_max_fd();
218 if (max_fd < 0)
219 return max_fd;
220
221 /* Refuse to do the loop over more too many elements. It's better to fail immediately than to
222 * spin the CPU for a long time. */
223 if (max_fd > MAX_FD_LOOP_LIMIT)
224 return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
225 "Refusing to loop over %d potential fds.",
226 max_fd);
227
228 for (int fd = 3; fd >= 0; fd = fd < max_fd ? fd + 1 : -1) {
229 int q;
230
231 if (fd_in_set(fd, except, n_except))
232 continue;
233
234 q = close_nointr(fd);
235 if (q < 0 && q != -EBADF && r >= 0)
236 r = q;
237 }
238
239 return r;
240 }
241
242 static bool have_close_range = true; /* Assume we live in the future */
243
close_all_fds_special_case(const int except[],size_t n_except)244 static int close_all_fds_special_case(const int except[], size_t n_except) {
245 assert(n_except == 0 || except);
246
247 /* Handles a few common special cases separately, since they are common and can be optimized really
248 * nicely, since we won't need sorting for them. Returns > 0 if the special casing worked, 0
249 * otherwise. */
250
251 if (!have_close_range)
252 return 0;
253
254 switch (n_except) {
255
256 case 0:
257 /* Close everything. Yay! */
258
259 if (close_range(3, -1, 0) >= 0)
260 return 1;
261
262 if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) {
263 have_close_range = false;
264 return 0;
265 }
266
267 return -errno;
268
269 case 1:
270 /* Close all but exactly one, then we don't need no sorting. This is a pretty common
271 * case, hence let's handle it specially. */
272
273 if ((except[0] <= 3 || close_range(3, except[0]-1, 0) >= 0) &&
274 (except[0] >= INT_MAX || close_range(MAX(3, except[0]+1), -1, 0) >= 0))
275 return 1;
276
277 if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) {
278 have_close_range = false;
279 return 0;
280 }
281
282 return -errno;
283
284 default:
285 return 0;
286 }
287 }
288
close_all_fds_without_malloc(const int except[],size_t n_except)289 int close_all_fds_without_malloc(const int except[], size_t n_except) {
290 int r;
291
292 assert(n_except == 0 || except);
293
294 r = close_all_fds_special_case(except, n_except);
295 if (r < 0)
296 return r;
297 if (r > 0) /* special case worked! */
298 return 0;
299
300 return close_all_fds_frugal(except, n_except);
301 }
302
close_all_fds(const int except[],size_t n_except)303 int close_all_fds(const int except[], size_t n_except) {
304 _cleanup_closedir_ DIR *d = NULL;
305 int r = 0;
306
307 assert(n_except == 0 || except);
308
309 r = close_all_fds_special_case(except, n_except);
310 if (r < 0)
311 return r;
312 if (r > 0) /* special case worked! */
313 return 0;
314
315 if (have_close_range) {
316 _cleanup_free_ int *sorted_malloc = NULL;
317 size_t n_sorted;
318 int *sorted;
319
320 /* In the best case we have close_range() to close all fds between a start and an end fd,
321 * which we can use on the "inverted" exception array, i.e. all intervals between all
322 * adjacent pairs from the sorted exception array. This changes loop complexity from O(n)
323 * where n is number of open fds to O(m⋅log(m)) where m is the number of fds to keep
324 * open. Given that we assume n ≫ m that's preferable to us. */
325
326 assert(n_except < SIZE_MAX);
327 n_sorted = n_except + 1;
328
329 if (n_sorted > 64) /* Use heap for large numbers of fds, stack otherwise */
330 sorted = sorted_malloc = new(int, n_sorted);
331 else
332 sorted = newa(int, n_sorted);
333
334 if (sorted) {
335 memcpy(sorted, except, n_except * sizeof(int));
336
337 /* Let's add fd 2 to the list of fds, to simplify the loop below, as this
338 * allows us to cover the head of the array the same way as the body */
339 sorted[n_sorted-1] = 2;
340
341 typesafe_qsort(sorted, n_sorted, cmp_int);
342
343 for (size_t i = 0; i < n_sorted-1; i++) {
344 int start, end;
345
346 start = MAX(sorted[i], 2); /* The first three fds shall always remain open */
347 end = MAX(sorted[i+1], 2);
348
349 assert(end >= start);
350
351 if (end - start <= 1)
352 continue;
353
354 /* Close everything between the start and end fds (both of which shall stay open) */
355 if (close_range(start + 1, end - 1, 0) < 0) {
356 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
357 return -errno;
358
359 have_close_range = false;
360 break;
361 }
362 }
363
364 if (have_close_range) {
365 /* The loop succeeded. Let's now close everything beyond the end */
366
367 if (sorted[n_sorted-1] >= INT_MAX) /* Dont let the addition below overflow */
368 return 0;
369
370 if (close_range(sorted[n_sorted-1] + 1, -1, 0) >= 0)
371 return 0;
372
373 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
374 return -errno;
375
376 have_close_range = false;
377 }
378 }
379
380 /* Fallback on OOM or if close_range() is not supported */
381 }
382
383 d = opendir("/proc/self/fd");
384 if (!d)
385 return close_all_fds_frugal(except, n_except); /* ultimate fallback if /proc/ is not available */
386
387 FOREACH_DIRENT(de, d, return -errno) {
388 int fd = -1, q;
389
390 if (!IN_SET(de->d_type, DT_LNK, DT_UNKNOWN))
391 continue;
392
393 if (safe_atoi(de->d_name, &fd) < 0)
394 /* Let's better ignore this, just in case */
395 continue;
396
397 if (fd < 3)
398 continue;
399
400 if (fd == dirfd(d))
401 continue;
402
403 if (fd_in_set(fd, except, n_except))
404 continue;
405
406 q = close_nointr(fd);
407 if (q < 0 && q != -EBADF && r >= 0) /* Valgrind has its own FD and doesn't want to have it closed */
408 r = q;
409 }
410
411 return r;
412 }
413
same_fd(int a,int b)414 int same_fd(int a, int b) {
415 struct stat sta, stb;
416 pid_t pid;
417 int r, fa, fb;
418
419 assert(a >= 0);
420 assert(b >= 0);
421
422 /* Compares two file descriptors. Note that semantics are quite different depending on whether we
423 * have kcmp() or we don't. If we have kcmp() this will only return true for dup()ed file
424 * descriptors, but not otherwise. If we don't have kcmp() this will also return true for two fds of
425 * the same file, created by separate open() calls. Since we use this call mostly for filtering out
426 * duplicates in the fd store this difference hopefully doesn't matter too much. */
427
428 if (a == b)
429 return true;
430
431 /* Try to use kcmp() if we have it. */
432 pid = getpid_cached();
433 r = kcmp(pid, pid, KCMP_FILE, a, b);
434 if (r == 0)
435 return true;
436 if (r > 0)
437 return false;
438 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
439 return -errno;
440
441 /* We don't have kcmp(), use fstat() instead. */
442 if (fstat(a, &sta) < 0)
443 return -errno;
444
445 if (fstat(b, &stb) < 0)
446 return -errno;
447
448 if (!stat_inode_same(&sta, &stb))
449 return false;
450
451 /* We consider all device fds different, since two device fds might refer to quite different device
452 * contexts even though they share the same inode and backing dev_t. */
453
454 if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
455 return false;
456
457 /* The fds refer to the same inode on disk, let's also check if they have the same fd flags. This is
458 * useful to distinguish the read and write side of a pipe created with pipe(). */
459 fa = fcntl(a, F_GETFL);
460 if (fa < 0)
461 return -errno;
462
463 fb = fcntl(b, F_GETFL);
464 if (fb < 0)
465 return -errno;
466
467 return fa == fb;
468 }
469
cmsg_close_all(struct msghdr * mh)470 void cmsg_close_all(struct msghdr *mh) {
471 struct cmsghdr *cmsg;
472
473 assert(mh);
474
475 CMSG_FOREACH(cmsg, mh)
476 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
477 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
478 }
479
fdname_is_valid(const char * s)480 bool fdname_is_valid(const char *s) {
481 const char *p;
482
483 /* Validates a name for $LISTEN_FDNAMES. We basically allow
484 * everything ASCII that's not a control character. Also, as
485 * special exception the ":" character is not allowed, as we
486 * use that as field separator in $LISTEN_FDNAMES.
487 *
488 * Note that the empty string is explicitly allowed
489 * here. However, we limit the length of the names to 255
490 * characters. */
491
492 if (!s)
493 return false;
494
495 for (p = s; *p; p++) {
496 if (*p < ' ')
497 return false;
498 if (*p >= 127)
499 return false;
500 if (*p == ':')
501 return false;
502 }
503
504 return p - s <= FDNAME_MAX;
505 }
506
fd_get_path(int fd,char ** ret)507 int fd_get_path(int fd, char **ret) {
508 int r;
509
510 r = readlink_malloc(FORMAT_PROC_FD_PATH(fd), ret);
511 if (r == -ENOENT) {
512 /* ENOENT can mean two things: that the fd does not exist or that /proc is not mounted. Let's make
513 * things debuggable and distinguish the two. */
514
515 if (proc_mounted() == 0)
516 return -ENOSYS; /* /proc is not available or not set up properly, we're most likely in some chroot
517 * environment. */
518 return -EBADF; /* The directory exists, hence it's the fd that doesn't. */
519 }
520
521 return r;
522 }
523
move_fd(int from,int to,int cloexec)524 int move_fd(int from, int to, int cloexec) {
525 int r;
526
527 /* Move fd 'from' to 'to', make sure FD_CLOEXEC remains equal if requested, and release the old fd. If
528 * 'cloexec' is passed as -1, the original FD_CLOEXEC is inherited for the new fd. If it is 0, it is turned
529 * off, if it is > 0 it is turned on. */
530
531 if (from < 0)
532 return -EBADF;
533 if (to < 0)
534 return -EBADF;
535
536 if (from == to) {
537
538 if (cloexec >= 0) {
539 r = fd_cloexec(to, cloexec);
540 if (r < 0)
541 return r;
542 }
543
544 return to;
545 }
546
547 if (cloexec < 0) {
548 int fl;
549
550 fl = fcntl(from, F_GETFD, 0);
551 if (fl < 0)
552 return -errno;
553
554 cloexec = !!(fl & FD_CLOEXEC);
555 }
556
557 r = dup3(from, to, cloexec ? O_CLOEXEC : 0);
558 if (r < 0)
559 return -errno;
560
561 assert(r == to);
562
563 safe_close(from);
564
565 return to;
566 }
567
fd_move_above_stdio(int fd)568 int fd_move_above_stdio(int fd) {
569 int flags, copy;
570 PROTECT_ERRNO;
571
572 /* Moves the specified file descriptor if possible out of the range [0…2], i.e. the range of
573 * stdin/stdout/stderr. If it can't be moved outside of this range the original file descriptor is
574 * returned. This call is supposed to be used for long-lasting file descriptors we allocate in our code that
575 * might get loaded into foreign code, and where we want ensure our fds are unlikely used accidentally as
576 * stdin/stdout/stderr of unrelated code.
577 *
578 * Note that this doesn't fix any real bugs, it just makes it less likely that our code will be affected by
579 * buggy code from others that mindlessly invokes 'fprintf(stderr, …' or similar in places where stderr has
580 * been closed before.
581 *
582 * This function is written in a "best-effort" and "least-impact" style. This means whenever we encounter an
583 * error we simply return the original file descriptor, and we do not touch errno. */
584
585 if (fd < 0 || fd > 2)
586 return fd;
587
588 flags = fcntl(fd, F_GETFD, 0);
589 if (flags < 0)
590 return fd;
591
592 if (flags & FD_CLOEXEC)
593 copy = fcntl(fd, F_DUPFD_CLOEXEC, 3);
594 else
595 copy = fcntl(fd, F_DUPFD, 3);
596 if (copy < 0)
597 return fd;
598
599 assert(copy > 2);
600
601 (void) close(fd);
602 return copy;
603 }
604
rearrange_stdio(int original_input_fd,int original_output_fd,int original_error_fd)605 int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd) {
606
607 int fd[3] = { /* Put together an array of fds we work on */
608 original_input_fd,
609 original_output_fd,
610 original_error_fd
611 };
612
613 int r, i,
614 null_fd = -1, /* if we open /dev/null, we store the fd to it here */
615 copy_fd[3] = { -1, -1, -1 }; /* This contains all fds we duplicate here temporarily, and hence need to close at the end */
616 bool null_readable, null_writable;
617
618 /* Sets up stdin, stdout, stderr with the three file descriptors passed in. If any of the descriptors is
619 * specified as -1 it will be connected with /dev/null instead. If any of the file descriptors is passed as
620 * itself (e.g. stdin as STDIN_FILENO) it is left unmodified, but the O_CLOEXEC bit is turned off should it be
621 * on.
622 *
623 * Note that if any of the passed file descriptors are > 2 they will be closed — both on success and on
624 * failure! Thus, callers should assume that when this function returns the input fds are invalidated.
625 *
626 * Note that when this function fails stdin/stdout/stderr might remain half set up!
627 *
628 * O_CLOEXEC is turned off for all three file descriptors (which is how it should be for
629 * stdin/stdout/stderr). */
630
631 null_readable = original_input_fd < 0;
632 null_writable = original_output_fd < 0 || original_error_fd < 0;
633
634 /* First step, open /dev/null once, if we need it */
635 if (null_readable || null_writable) {
636
637 /* Let's open this with O_CLOEXEC first, and convert it to non-O_CLOEXEC when we move the fd to the final position. */
638 null_fd = open("/dev/null", (null_readable && null_writable ? O_RDWR :
639 null_readable ? O_RDONLY : O_WRONLY) | O_CLOEXEC);
640 if (null_fd < 0) {
641 r = -errno;
642 goto finish;
643 }
644
645 /* If this fd is in the 0…2 range, let's move it out of it */
646 if (null_fd < 3) {
647 int copy;
648
649 copy = fcntl(null_fd, F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
650 if (copy < 0) {
651 r = -errno;
652 goto finish;
653 }
654
655 CLOSE_AND_REPLACE(null_fd, copy);
656 }
657 }
658
659 /* Let's assemble fd[] with the fds to install in place of stdin/stdout/stderr */
660 for (i = 0; i < 3; i++) {
661
662 if (fd[i] < 0)
663 fd[i] = null_fd; /* A negative parameter means: connect this one to /dev/null */
664 else if (fd[i] != i && fd[i] < 3) {
665 /* 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. */
666 copy_fd[i] = fcntl(fd[i], F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
667 if (copy_fd[i] < 0) {
668 r = -errno;
669 goto finish;
670 }
671
672 fd[i] = copy_fd[i];
673 }
674 }
675
676 /* At this point we now have the fds to use in fd[], and they are all above the stdio range, so that we
677 * have freedom to move them around. If the fds already were at the right places then the specific fds are
678 * -1. Let's now move them to the right places. This is the point of no return. */
679 for (i = 0; i < 3; i++) {
680
681 if (fd[i] == i) {
682
683 /* fd is already in place, but let's make sure O_CLOEXEC is off */
684 r = fd_cloexec(i, false);
685 if (r < 0)
686 goto finish;
687
688 } else {
689 assert(fd[i] > 2);
690
691 if (dup2(fd[i], i) < 0) { /* Turns off O_CLOEXEC on the new fd. */
692 r = -errno;
693 goto finish;
694 }
695 }
696 }
697
698 r = 0;
699
700 finish:
701 /* Close the original fds, but only if they were outside of the stdio range. Also, properly check for the same
702 * fd passed in multiple times. */
703 safe_close_above_stdio(original_input_fd);
704 if (original_output_fd != original_input_fd)
705 safe_close_above_stdio(original_output_fd);
706 if (original_error_fd != original_input_fd && original_error_fd != original_output_fd)
707 safe_close_above_stdio(original_error_fd);
708
709 /* Close the copies we moved > 2 */
710 for (i = 0; i < 3; i++)
711 safe_close(copy_fd[i]);
712
713 /* Close our null fd, if it's > 2 */
714 safe_close_above_stdio(null_fd);
715
716 return r;
717 }
718
fd_reopen(int fd,int flags)719 int fd_reopen(int fd, int flags) {
720 int new_fd, r;
721
722 /* Reopens the specified fd with new flags. This is useful for convert an O_PATH fd into a regular one, or to
723 * turn O_RDWR fds into O_RDONLY fds.
724 *
725 * This doesn't work on sockets (since they cannot be open()ed, ever).
726 *
727 * This implicitly resets the file read index to 0. */
728
729 if (FLAGS_SET(flags, O_DIRECTORY)) {
730 /* If we shall reopen the fd as directory we can just go via "." and thus bypass the whole
731 * magic /proc/ directory, and make ourselves independent of that being mounted. */
732 new_fd = openat(fd, ".", flags);
733 if (new_fd < 0)
734 return -errno;
735
736 return new_fd;
737 }
738
739 new_fd = open(FORMAT_PROC_FD_PATH(fd), flags);
740 if (new_fd < 0) {
741 if (errno != ENOENT)
742 return -errno;
743
744 r = proc_mounted();
745 if (r == 0)
746 return -ENOSYS; /* if we have no /proc/, the concept is not implementable */
747
748 return r > 0 ? -EBADF : -ENOENT; /* If /proc/ is definitely around then this means the fd is
749 * not valid, otherwise let's propagate the original
750 * error */
751 }
752
753 return new_fd;
754 }
755
read_nr_open(void)756 int read_nr_open(void) {
757 _cleanup_free_ char *nr_open = NULL;
758 int r;
759
760 /* Returns the kernel's current fd limit, either by reading it of /proc/sys if that works, or using the
761 * hard-coded default compiled-in value of current kernels (1M) if not. This call will never fail. */
762
763 r = read_one_line_file("/proc/sys/fs/nr_open", &nr_open);
764 if (r < 0)
765 log_debug_errno(r, "Failed to read /proc/sys/fs/nr_open, ignoring: %m");
766 else {
767 int v;
768
769 r = safe_atoi(nr_open, &v);
770 if (r < 0)
771 log_debug_errno(r, "Failed to parse /proc/sys/fs/nr_open value '%s', ignoring: %m", nr_open);
772 else
773 return v;
774 }
775
776 /* If we fail, fall back to the hard-coded kernel limit of 1024 * 1024. */
777 return 1024 * 1024;
778 }
779
780 /* This is here because it's fd-related and is called from sd-journal code. Other btrfs-related utilities are
781 * in src/shared, but libsystemd must not link to libsystemd-shared, see docs/ARCHITECTURE.md. */
btrfs_defrag_fd(int fd)782 int btrfs_defrag_fd(int fd) {
783 int r;
784
785 assert(fd >= 0);
786
787 r = fd_verify_regular(fd);
788 if (r < 0)
789 return r;
790
791 return RET_NERRNO(ioctl(fd, BTRFS_IOC_DEFRAG, NULL));
792 }
793
fd_get_diskseq(int fd,uint64_t * ret)794 int fd_get_diskseq(int fd, uint64_t *ret) {
795 uint64_t diskseq;
796
797 assert(fd >= 0);
798 assert(ret);
799
800 if (ioctl(fd, BLKGETDISKSEQ, &diskseq) < 0) {
801 /* Note that the kernel is weird: non-existing ioctls currently return EINVAL
802 * rather than ENOTTY on loopback block devices. They should fix that in the kernel,
803 * but in the meantime we accept both here. */
804 if (!ERRNO_IS_NOT_SUPPORTED(errno) && errno != EINVAL)
805 return -errno;
806
807 return -EOPNOTSUPP;
808 }
809
810 *ret = diskseq;
811
812 return 0;
813 }
814