Debian Codegraph @

src/basic/fd-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <linux/fs.h>
5 #include <sys/ioctl.h>
6 #include <sys/kcmp.h>
7 #include <sys/resource.h>
8 #include <sys/stat.h>
9 #include <unistd.h>
10
11 #include "alloc-util.h"
12 #include "dirent-util.h"
13 #include "errno-util.h"
14 #include "fd-util.h"
15 #include "fileio.h"
16 #include "format-util.h"
17 #include "fs-util.h"
18 #include "log.h"
19 #include "parse-util.h"
20 #include "path-util.h"
21 #include "process-util.h"
22 #include "sort-util.h"
23 #include "stat-util.h"
24 #include "stdio-util.h"
25 #include "string-util.h"
26
27 /* The maximum number of iterations in the loop to close descriptors in the fallback case
28 * when /proc/self/fd/ is inaccessible. */
29 #define MAX_FD_LOOP_LIMIT (1024*1024)
30
31 int close_nointr(int fd) {
32 assert(fd >= 0);
33
34 if (close(fd) >= 0)
35 return 0;
36
37 /*
38 * Just ignore EINTR; a retry loop is the wrong thing to do on
39 * Linux.
40 *
41 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
42 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
43 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
44 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
45 */
46 if (errno == EINTR)
47 return 0;
48
49 return -errno;
50 }
51
52 int safe_close(int fd) {
53 /*
54 * Like close_nointr() but cannot fail. Guarantees errno is unchanged. Is a noop for negative fds,
55 * and returns -EBADF, so that it can be used in this syntax:
56 *
57 * fd = safe_close(fd);
58 */
59
60 if (fd >= 0) {
61 PROTECT_ERRNO;
62
63 /* The kernel might return pretty much any error code
64 * via close(), but the fd will be closed anyway. The
65 * only condition we want to check for here is whether
66 * the fd was invalid at all... */
67
68 assert_se(close_nointr(fd) != -EBADF);
69 }
70
71 return -EBADF;
72 }
73
74 void safe_close_pair(int p[static 2]) {
75 assert(p);
76
77 if (p[0] == p[1]) {
78 /* Special case pairs which use the same fd in both
79 * directions... */
80 p[0] = p[1] = safe_close(p[0]);
81 return;
82 }
83
84 p[0] = safe_close(p[0]);
85 p[1] = safe_close(p[1]);
86 }
87
88 void close_many(const int fds[], size_t n_fds) {
89 assert(fds || n_fds == 0);
90
91 FOREACH_ARRAY(fd, fds, n_fds)
92 safe_close(*fd);
93 }
94
95 void close_many_unset(int fds[], size_t n_fds) {
96 assert(fds || n_fds == 0);
97
98 FOREACH_ARRAY(fd, fds, n_fds)
99 *fd = safe_close(*fd);
100 }
101
102 void close_many_and_free(int *fds, size_t n_fds) {
103 assert(fds || n_fds == 0);
104
105 close_many(fds, n_fds);
106 free(fds);
107 }
108
109 int fclose_nointr(FILE *f) {
110 assert(f);
111
112 /* Same as close_nointr(), but for fclose() */
113
114 errno = 0; /* Extra safety: if the FILE* object is not encapsulating an fd, it might not set errno
115 * correctly. Let's hence initialize it to zero first, so that we aren't confused by any
116 * prior errno here */
117 if (fclose(f) == 0)
118 return 0;
119
120 if (errno == EINTR)
121 return 0;
122
123 return errno_or_else(EIO);
124 }
125
126 FILE* safe_fclose(FILE *f) {
127
128 /* Same as safe_close(), but for fclose() */
129
130 if (f) {
131 PROTECT_ERRNO;
132
133 assert_se(fclose_nointr(f) != -EBADF);
134 }
135
136 return NULL;
137 }
138
139 DIR* safe_closedir(DIR *d) {
140
141 if (d) {
142 PROTECT_ERRNO;
143
144 assert_se(closedir(d) >= 0 || errno != EBADF);
145 }
146
147 return NULL;
148 }
149
150 int fd_nonblock(int fd, bool nonblock) {
151 int flags, nflags;
152
153 assert(fd >= 0);
154
155 flags = fcntl(fd, F_GETFL, 0);
156 if (flags < 0)
157 return -errno;
158
159 nflags = UPDATE_FLAG(flags, O_NONBLOCK, nonblock);
160 if (nflags == flags)
161 return 0;
162
163 if (fcntl(fd, F_SETFL, nflags) < 0)
164 return -errno;
165
166 return 1;
167 }
168
169 void nonblock_resetp(int *fd) {
170 assert(fd);
171
172 PROTECT_ERRNO;
173
174 if (*fd >= 0)
175 (void) fd_nonblock(*fd, false);
176 }
177
178 int stdio_disable_nonblock(void) {
179 int ret = 0;
180
181 /* stdin/stdout/stderr really should have O_NONBLOCK, which would confuse apps if left on, as
182 * write()s might unexpectedly fail with EAGAIN. */
183
184 RET_GATHER(ret, fd_nonblock(STDIN_FILENO, false));
185 RET_GATHER(ret, fd_nonblock(STDOUT_FILENO, false));
186 RET_GATHER(ret, fd_nonblock(STDERR_FILENO, false));
187
188 return ret;
189 }
190
191 int fd_cloexec(int fd, bool cloexec) {
192 int flags, nflags;
193
194 assert(fd >= 0);
195
196 flags = fcntl(fd, F_GETFD, 0);
197 if (flags < 0)
198 return -errno;
199
200 nflags = UPDATE_FLAG(flags, FD_CLOEXEC, cloexec);
201 if (nflags == flags)
202 return 0;
203
204 return RET_NERRNO(fcntl(fd, F_SETFD, nflags));
205 }
206
207 int fd_cloexec_many(const int fds[], size_t n_fds, bool cloexec) {
208 int r = 0;
209
210 assert(fds || n_fds == 0);
211
212 FOREACH_ARRAY(fd, fds, n_fds) {
213 if (*fd < 0) /* Skip gracefully over already invalidated fds */
214 continue;
215
216 RET_GATHER(r, fd_cloexec(*fd, cloexec));
217 }
218
219 return r;
220 }
221
222 static bool fd_in_set(int fd, const int fds[], size_t n_fds) {
223 assert(fd >= 0);
224 assert(fds || n_fds == 0);
225
226 FOREACH_ARRAY(i, fds, n_fds) {
227 if (*i < 0)
228 continue;
229
230 if (*i == fd)
231 return true;
232 }
233
234 return false;
235 }
236
237 int get_max_fd(void) {
238 struct rlimit rl;
239 rlim_t m;
240
241 /* Return the highest possible fd, based RLIMIT_NOFILE, but enforcing FD_SETSIZE-1 as lower boundary
242 * and INT_MAX as upper boundary. */
243
244 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
245 return -errno;
246
247 m = MAX(rl.rlim_cur, rl.rlim_max);
248 if (m < FD_SETSIZE) /* Let's always cover at least 1024 fds */
249 return FD_SETSIZE-1;
250
251 if (m == RLIM_INFINITY || m > INT_MAX) /* Saturate on overflow. After all fds are "int", hence can
252 * never be above INT_MAX */
253 return INT_MAX;
254
255 return (int) (m - 1);
256 }
257
258 int close_all_fds_frugal(const int except[], size_t n_except) {
259 int max_fd, r = 0;
260
261 assert(except || n_except == 0);
262
263 /* This is the inner fallback core of close_all_fds(). This never calls malloc() or so and hence is
264 * safe to be called in signal handler context. Most users should call close_all_fds(), but when we
265 * assume we are called from signal handler context, then use this simpler call instead. */
266
267 max_fd = get_max_fd();
268 if (max_fd < 0)
269 return max_fd;
270
271 /* Refuse to do the loop over more too many elements. It's better to fail immediately than to
272 * spin the CPU for a long time. */
273 if (max_fd > MAX_FD_LOOP_LIMIT)
274 return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
275 "Refusing to loop over %d potential fds.", max_fd);
276
277 for (int fd = 3; fd >= 0; fd = fd < max_fd ? fd + 1 : -EBADF) {
278 int q;
279
280 if (fd_in_set(fd, except, n_except))
281 continue;
282
283 q = close_nointr(fd);
284 if (q != -EBADF)
285 RET_GATHER(r, q);
286 }
287
288 return r;
289 }
290
291 static int close_all_fds_special_case(const int except[], size_t n_except) {
292 assert(n_except == 0 || except);
293
294 /* Handles a few common special cases separately, since they are common and can be optimized really
295 * nicely, since we won't need sorting for them. Returns > 0 if the special casing worked, 0
296 * otherwise. */
297
298 if (n_except == 1 && except[0] < 0) /* Minor optimization: if we only got one fd, and it's invalid,
299 * we got none */
300 n_except = 0;
301
302 switch (n_except) {
303
304 case 0:
305 /* Close everything. Yay! */
306 if (close_range(3, INT_MAX, 0) < 0)
307 return -errno;
308
309 return 1;
310
311 case 1:
312 /* Close all but exactly one, then we don't need no sorting. This is a pretty common
313 * case, hence let's handle it specially. */
314
315 if (except[0] > 3 && close_range(3, except[0] - 1, 0) < 0)
316 return -errno;
317
318 if (except[0] < INT_MAX && close_range(MAX(3, except[0] + 1), -1, 0) < 0)
319 return -errno;
320
321 return 1;
322
323 default:
324 return 0;
325 }
326 }
327
328 int close_all_fds_without_malloc(const int except[], size_t n_except) {
329 int r;
330
331 assert(n_except == 0 || except);
332
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;
338
339 return close_all_fds_frugal(except, n_except);
340 }
341
342 int close_all_fds(const int except[], size_t n_except) {
343 int r;
344
345 assert(n_except == 0 || except);
346
347 r = close_all_fds_special_case(except, n_except);
348 if (r < 0)
349 return r;
350 if (r > 0) /* special case worked! */
351 return 0;
352
353 _cleanup_free_ int *sorted_malloc = NULL;
354 size_t n_sorted;
355 int *sorted;
356
357 /* In the best case we have close_range() to close all fds between a start and an end fd, which we
358 * can use on the "inverted" exception array, i.e. all intervals between all adjacent pairs from the
359 * sorted exception array. This changes loop complexity from O(n) where n is number of open fds to
360 * O(m⋅log(m)) where m is the number of fds to keep open. Given that we assume n ≫ m that's
361 * preferable to us. */
362
363 assert(n_except < SIZE_MAX);
364 n_sorted = n_except + 1;
365
366 if (n_sorted > ALLOCA_MAX / sizeof(int)) /* Use heap for large numbers of fds, stack otherwise */
367 sorted = sorted_malloc = new(int, n_sorted);
368 else
369 sorted = newa(int, n_sorted);
370
371 if (!sorted) /* Fallback on OOM. */
372 return close_all_fds_frugal(except, n_except);
373
374 memcpy(sorted, except, n_except * sizeof(int));
375
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;
379
380 typesafe_qsort(sorted, n_sorted, cmp_int);
381
382 for (size_t i = 0; i < n_sorted-1; i++) {
383 int start, end;
384
385 start = MAX(sorted[i], 2); /* The first three fds shall always remain open */
386 end = MAX(sorted[i+1], 2);
387
388 assert(end >= start);
389
390 if (end - start <= 1)
391 continue;
392
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)
395 return -errno;
396 }
397
398 /* The loop succeeded. Let's now close everything beyond the end */
399
400 if (sorted[n_sorted-1] >= INT_MAX) /* Dont let the addition below overflow */
401 return 0;
402
403 if (close_range(sorted[n_sorted-1] + 1, INT_MAX, 0) < 0)
404 return -errno;
405
406 return 0;
407 }
408
409 int pack_fds(int fds[], size_t n_fds) {
410 if (n_fds <= 0)
411 return 0;
412
413 /* Shifts around the fds in the provided array such that they
414 * all end up packed next to each-other, in order, starting
415 * from SD_LISTEN_FDS_START. This must be called after close_all_fds();
416 * it is likely to freeze up otherwise. You should probably use safe_fork_full
417 * with FORK_CLOSE_ALL_FDS|FORK_PACK_FDS set, to ensure that this is done correctly.
418 * The fds array is modified in place with the new FD numbers. */
419
420 assert(fds);
421
422 for (int start = 0;;) {
423 int restart_from = -1;
424
425 for (int i = start; i < (int) n_fds; i++) {
426 int nfd;
427
428 /* Already at right index? */
429 if (fds[i] == i + 3)
430 continue;
431
432 nfd = fcntl(fds[i], F_DUPFD, i + 3);
433 if (nfd < 0)
434 return -errno;
435
436 safe_close(fds[i]);
437 fds[i] = nfd;
438
439 /* Hmm, the fd we wanted isn't free? Then
440 * let's remember that and try again from here */
441 if (nfd != i + 3 && restart_from < 0)
442 restart_from = i;
443 }
444
445 if (restart_from < 0)
446 break;
447
448 start = restart_from;
449 }
450
451 assert(fds[0] == 3);
452
453 return 0;
454 }
455
456 int fd_validate(int fd) {
457 if (fd < 0)
458 return -EBADF;
459
460 if (fcntl(fd, F_GETFD) < 0)
461 return -errno;
462
463 return 0;
464 }
465
466 int same_fd(int a, int b) {
467 struct stat sta, stb;
468 pid_t pid;
469 int r, fa, fb;
470
471 assert(a >= 0);
472 assert(b >= 0);
473
474 /* Compares two file descriptors. Note that semantics are quite different depending on whether we
475 * have F_DUPFD_QUERY/kcmp() or we don't. If we have F_DUPFD_QUERY/kcmp() this will only return true
476 * for dup()ed file descriptors, but not otherwise. If we don't have F_DUPFD_QUERY/kcmp() this will
477 * also return true for two fds of the same file, created by separate open() calls. Since we use this
478 * call mostly for filtering out duplicates in the fd store this difference hopefully doesn't matter
479 * too much.
480 *
481 * Guarantees that if either of the passed fds is not allocated we'll return -EBADF. */
482
483 if (a == b) {
484 /* Let's validate that the fd is valid */
485 r = fd_validate(a);
486 if (r < 0)
487 return r;
488
489 return true;
490 }
491
492 /* Try to use F_DUPFD_QUERY if we have it first, as it is the nicest API */
493 r = fcntl(a, F_DUPFD_QUERY, b);
494 if (r > 0)
495 return true;
496 if (r == 0) {
497 /* The kernel will return 0 in case the first fd is allocated, but the 2nd is not. (Which is different in the kcmp() case) Explicitly validate it hence. */
498 r = fd_validate(b);
499 if (r < 0)
500 return r;
501
502 return false;
503 }
504 /* On old kernels (< 6.10) that do not support F_DUPFD_QUERY this will return EINVAL for regular fds, and EBADF on O_PATH fds. Confusing. */
505 if (errno == EBADF) {
506 /* EBADF could mean two things: the first fd is not valid, or it is valid and is O_PATH and
507 * F_DUPFD_QUERY is not supported. Let's validate the fd explicitly, to distinguish this
508 * case. */
509 r = fd_validate(a);
510 if (r < 0)
511 return r;
512
513 /* If the fd is valid, but we got EBADF, then let's try kcmp(). */
514 } else if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno) && errno != EINVAL)
515 return -errno;
516
517 /* Try to use kcmp() if we have it. */
518 pid = getpid_cached();
519 r = kcmp(pid, pid, KCMP_FILE, a, b);
520 if (r >= 0)
521 return !r;
522 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
523 return -errno;
524
525 /* We have neither F_DUPFD_QUERY nor kcmp(), use fstat() instead. */
526 if (fstat(a, &sta) < 0)
527 return -errno;
528
529 if (fstat(b, &stb) < 0)
530 return -errno;
531
532 if (!stat_inode_same(&sta, &stb))
533 return false;
534
535 /* We consider all device fds different, since two device fds might refer to quite different device
536 * contexts even though they share the same inode and backing dev_t. */
537
538 if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
539 return false;
540
541 /* The fds refer to the same inode on disk, let's also check if they have the same fd flags. This is
542 * useful to distinguish the read and write side of a pipe created with pipe(). */
543 fa = fcntl(a, F_GETFL);
544 if (fa < 0)
545 return -errno;
546
547 fb = fcntl(b, F_GETFL);
548 if (fb < 0)
549 return -errno;
550
551 return fa == fb;
552 }
553
554 bool fdname_is_valid(const char *s) {
555 const char *p;
556
557 /* Validates a name for $LISTEN_FDNAMES. We basically allow
558 * everything ASCII that's not a control character. Also, as
559 * special exception the ":" character is not allowed, as we
560 * use that as field separator in $LISTEN_FDNAMES.
561 *
562 * Note that the empty string is explicitly allowed
563 * here. However, we limit the length of the names to 255
564 * characters. */
565
566 if (!s)
567 return false;
568
569 for (p = s; *p; p++) {
570 if (*p < ' ')
571 return false;
572 if (*p >= 127)
573 return false;
574 if (*p == ':')
575 return false;
576 }
577
578 return p - s <= FDNAME_MAX;
579 }
580
581 int fd_get_path(int fd, char **ret) {
582 int r;
583
584 assert(wildcard_fd_is_valid(fd));
585
586 if (fd == AT_FDCWD)
587 return safe_getcwd(ret);
588 if (fd == XAT_FDROOT)
589 return strdup_to(ret, "/");
590
591 r = readlink_malloc(FORMAT_PROC_FD_PATH(fd), ret);
592 if (r == -ENOENT)
593 return proc_fd_enoent_errno();
594 return r;
595 }
596
597 int move_fd(int from, int to, int cloexec) {
598 int r;
599
600 /* Move fd 'from' to 'to', make sure FD_CLOEXEC remains equal if requested, and release the old fd. If
601 * 'cloexec' is passed as -1, the original FD_CLOEXEC is inherited for the new fd. If it is 0, it is turned
602 * off, if it is > 0 it is turned on. */
603
604 if (from < 0)
605 return -EBADF;
606 if (to < 0)
607 return -EBADF;
608
609 if (from == to) {
610
611 if (cloexec >= 0) {
612 r = fd_cloexec(to, cloexec);
613 if (r < 0)
614 return r;
615 }
616
617 return to;
618 }
619
620 if (cloexec < 0) {
621 int fl;
622
623 fl = fcntl(from, F_GETFD, 0);
624 if (fl < 0)
625 return -errno;
626
627 cloexec = FLAGS_SET(fl, FD_CLOEXEC);
628 }
629
630 r = dup3(from, to, cloexec ? O_CLOEXEC : 0);
631 if (r < 0)
632 return -errno;
633
634 assert(r == to);
635
636 safe_close(from);
637
638 return to;
639 }
640
641 int fd_move_above_stdio(int fd) {
642 int flags, copy;
643 PROTECT_ERRNO;
644
645 /* Moves the specified file descriptor if possible out of the range [0…2], i.e. the range of
646 * stdin/stdout/stderr. If it can't be moved outside of this range the original file descriptor is
647 * returned. This call is supposed to be used for long-lasting file descriptors we allocate in our code that
648 * might get loaded into foreign code, and where we want ensure our fds are unlikely used accidentally as
649 * stdin/stdout/stderr of unrelated code.
650 *
651 * Note that this doesn't fix any real bugs, it just makes it less likely that our code will be affected by
652 * buggy code from others that mindlessly invokes 'fprintf(stderr, …' or similar in places where stderr has
653 * been closed before.
654 *
655 * This function is written in a "best-effort" and "least-impact" style. This means whenever we encounter an
656 * error we simply return the original file descriptor, and we do not touch errno. */
657
658 if (fd < 0 || fd > 2)
659 return fd;
660
661 flags = fcntl(fd, F_GETFD, 0);
662 if (flags < 0)
663 return fd;
664
665 if (flags & FD_CLOEXEC)
666 copy = fcntl(fd, F_DUPFD_CLOEXEC, 3);
667 else
668 copy = fcntl(fd, F_DUPFD, 3);
669 if (copy < 0)
670 return fd;
671
672 assert(copy > 2);
673
674 (void) close(fd);
675 return copy;
676 }
677
678 int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd) {
679 int fd[3] = { original_input_fd, /* Put together an array of fds we work on */
680 original_output_fd,
681 original_error_fd },
682 null_fd = -EBADF, /* If we open /dev/null, we store the fd to it here */
683 copy_fd[3] = EBADF_TRIPLET, /* This contains all fds we duplicate here
684 * temporarily, and hence need to close at the end. */
685 r;
686 bool null_readable, null_writable;
687
688 /* Sets up stdin, stdout, stderr with the three file descriptors passed in. If any of the descriptors
689 * is specified as -EBADF it will be connected with /dev/null instead. If any of the file descriptors
690 * is passed as itself (e.g. stdin as STDIN_FILENO) it is left unmodified, but the O_CLOEXEC bit is
691 * turned off should it be on.
692 *
693 * Note that if any of the passed file descriptors are > 2 they will be closed — both on success and
694 * on failure! Thus, callers should assume that when this function returns the input fds are
695 * invalidated.
696 *
697 * Note that when this function fails stdin/stdout/stderr might remain half set up!
698 *
699 * O_CLOEXEC is turned off for all three file descriptors (which is how it should be for
700 * stdin/stdout/stderr). */
701
702 null_readable = original_input_fd < 0;
703 null_writable = original_output_fd < 0 || original_error_fd < 0;
704
705 /* First step, open /dev/null once, if we need it */
706 if (null_readable || null_writable) {
707
708 /* Let's open this with O_CLOEXEC first, and convert it to non-O_CLOEXEC when we move the fd to the final position. */
709 null_fd = open("/dev/null", (null_readable && null_writable ? O_RDWR :
710 null_readable ? O_RDONLY : O_WRONLY) | O_CLOEXEC);
711 if (null_fd < 0) {
712 r = -errno;
713 goto finish;
714 }
715
716 /* If this fd is in the 0…2 range, let's move it out of it */
717 if (null_fd < 3) {
718 int copy;
719
720 copy = fcntl(null_fd, F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
721 if (copy < 0) {
722 r = -errno;
723 goto finish;
724 }
725
726 close_and_replace(null_fd, copy);
727 }
728 }
729
730 /* Let's assemble fd[] with the fds to install in place of stdin/stdout/stderr */
731 for (int i = 0; i < 3; i++)
732 if (fd[i] < 0)
733 fd[i] = null_fd; /* A negative parameter means: connect this one to /dev/null */
734 else if (fd[i] != i && fd[i] < 3) {
735 /* 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. */
736 copy_fd[i] = fcntl(fd[i], F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
737 if (copy_fd[i] < 0) {
738 r = -errno;
739 goto finish;
740 }
741
742 fd[i] = copy_fd[i];
743 }
744
745 /* At this point we now have the fds to use in fd[], and they are all above the stdio range, so that
746 * we have freedom to move them around. If the fds already were at the right places then the specific
747 * fds are -EBADF. Let's now move them to the right places. This is the point of no return. */
748 for (int i = 0; i < 3; i++)
749 if (fd[i] == i) {
750 /* fd is already in place, but let's make sure O_CLOEXEC is off */
751 r = fd_cloexec(i, false);
752 if (r < 0)
753 goto finish;
754 } else {
755 assert(fd[i] > 2);
756
757 if (dup2(fd[i], i) < 0) { /* Turns off O_CLOEXEC on the new fd. */
758 r = -errno;
759 goto finish;
760 }
761 }
762
763 r = 0;
764
765 finish:
766 /* Close the original fds, but only if they were outside of the stdio range. Also, properly check for the same
767 * fd passed in multiple times. */
768 safe_close_above_stdio(original_input_fd);
769 if (original_output_fd != original_input_fd)
770 safe_close_above_stdio(original_output_fd);
771 if (original_error_fd != original_input_fd && original_error_fd != original_output_fd)
772 safe_close_above_stdio(original_error_fd);
773
774 /* Close the copies we moved > 2 */
775 close_many(copy_fd, 3);
776
777 /* Close our null fd, if it's > 2 */
778 safe_close_above_stdio(null_fd);
779
780 return r;
781 }
782
783 int fd_reopen(int fd, int flags) {
784 assert(wildcard_fd_is_valid(fd));
785 assert(!FLAGS_SET(flags, O_CREAT));
786
787 /* Reopens the specified fd with new flags. This is useful for convert an O_PATH fd into a regular one, or to
788 * turn O_RDWR fds into O_RDONLY fds.
789 *
790 * This doesn't work on sockets (since they cannot be open()ed, ever).
791 *
792 * This implicitly resets the file read index to 0.
793 *
794 * If AT_FDCWD is specified as file descriptor gets an fd to the current cwd.
795 *
796 * If XAT_FDROOT is specified as fd get an fd to the root directory.
797 *
798 * If the specified file descriptor refers to a symlink via O_PATH, then this function cannot be used
799 * to follow that symlink. Because we cannot have non-O_PATH fds to symlinks reopening it without
800 * O_PATH will always result in -ELOOP. Or in other words: if you have an O_PATH fd to a symlink you
801 * can reopen it only if you pass O_PATH again. */
802
803 if (FLAGS_SET(flags, O_NOFOLLOW))
804 /* O_NOFOLLOW is not allowed in fd_reopen(), because after all this is primarily implemented
805 * via a symlink-based interface in /proc/self/fd. Let's refuse this here early. Note that
806 * the kernel would generate ELOOP here too, hence this manual check is mostly redundant –
807 * the only reason we add it here is so that the O_DIRECTORY special case (see below) behaves
808 * the same way as the non-O_DIRECTORY case. */
809 return -ELOOP;
810
811 if (fd == XAT_FDROOT)
812 return RET_NERRNO(open("/", flags | O_DIRECTORY));
813
814 if (FLAGS_SET(flags, O_DIRECTORY) || fd == AT_FDCWD)
815 /* If we shall reopen the fd as directory we can just go via "." and thus bypass the whole
816 * magic /proc/ directory, and make ourselves independent of that being mounted. */
817 return RET_NERRNO(openat(fd, ".", flags | O_DIRECTORY));
818
819 int new_fd = open(FORMAT_PROC_FD_PATH(fd), flags);
820 if (new_fd < 0) {
821 if (errno != ENOENT)
822 return -errno;
823
824 return proc_fd_enoent_errno();
825 }
826
827 return new_fd;
828 }
829
830 int fd_reopen_propagate_append_and_position(int fd, int flags) {
831 /* Invokes fd_reopen(fd, flags), but propagates O_APPEND if set on original fd, and also tries to
832 * keep current file position.
833 *
834 * You should use this if the original fd potentially is O_APPEND, otherwise we get rather
835 * "unexpected" behavior. Unless you intentionally want to overwrite pre-existing data, and have
836 * your output overwritten by the next user.
837 *
838 * Use case: "systemd-run --pty >> some-log".
839 *
840 * The "keep position" part is obviously nonsense for the O_APPEND case, but should reduce surprises
841 * if someone carefully pre-positioned the passed in original input or non-append output FDs. */
842
843 assert(fd >= 0);
844 assert(!(flags & (O_APPEND|O_DIRECTORY)));
845
846 int existing_flags = fcntl(fd, F_GETFL);
847 if (existing_flags < 0)
848 return -errno;
849
850 int new_fd = fd_reopen(fd, flags | (existing_flags & O_APPEND));
851 if (new_fd < 0)
852 return new_fd;
853
854 /* Try to adjust the offset, but ignore errors. */
855 off_t p = lseek(fd, 0, SEEK_CUR);
856 if (p > 0) {
857 off_t new_p = lseek(new_fd, p, SEEK_SET);
858 if (new_p < 0)
859 log_debug_errno(errno,
860 "Failed to propagate file position for re-opened fd %d, ignoring: %m",
861 fd);
862 else if (new_p != p)
863 log_debug("Failed to propagate file position for re-opened fd %d (%lld != %lld), ignoring.",
864 fd, (long long) new_p, (long long) p);
865 }
866
867 return new_fd;
868 }
869
870 int fd_reopen_condition(
871 int fd,
872 int flags,
873 int mask,
874 int *ret_new_fd) {
875
876 int r, new_fd;
877
878 assert(fd >= 0);
879 assert(!FLAGS_SET(flags, O_CREAT));
880 assert(ret_new_fd);
881
882 /* Invokes fd_reopen(fd, flags), but only if the existing F_GETFL flags don't match the specified
883 * flags (masked by the specified mask). This is useful for converting O_PATH fds into real fds if
884 * needed, but only then. */
885
886 r = fcntl(fd, F_GETFL);
887 if (r < 0)
888 return -errno;
889
890 if ((r & mask) == (flags & mask)) {
891 *ret_new_fd = -EBADF;
892 return fd;
893 }
894
895 new_fd = fd_reopen(fd, flags);
896 if (new_fd < 0)
897 return new_fd;
898
899 *ret_new_fd = new_fd;
900 return new_fd;
901 }
902
903 int fd_is_opath(int fd) {
904 int r;
905
906 assert(fd >= 0);
907
908 r = fcntl(fd, F_GETFL);
909 if (r < 0)
910 return -errno;
911
912 return FLAGS_SET(r, O_PATH);
913 }
914
915 int fd_vet_accmode(int fd, int mode) {
916 int flags;
917
918 /* Check if fd is opened with desired access mode.
919 *
920 * Returns > 0 on strict match, == 0 if opened for both reading and writing (partial match),
921 * -EPROTOTYPE otherwise. O_PATH fds are always refused with -EBADFD.
922 *
923 * Note that while on O_DIRECTORY -EISDIR will be returned, this should not be relied upon as
924 * the flag might not have been specified when open() was called originally. */
925
926 assert(fd >= 0);
927 assert(IN_SET(mode, O_RDONLY, O_WRONLY, O_RDWR));
928
929 flags = fcntl(fd, F_GETFL);
930 if (flags < 0)
931 return -errno;
932
933 /* O_TMPFILE in userspace is defined with O_DIRECTORY OR'ed in, so explicitly permit it.
934 *
935 * C.f. https://elixir.bootlin.com/linux/v6.17.7/source/include/uapi/asm-generic/fcntl.h#L92 */
936 if (FLAGS_SET(flags, O_DIRECTORY) && !FLAGS_SET(flags, O_TMPFILE))
937 return -EISDIR;
938
939 if (FLAGS_SET(flags, O_PATH))
940 return -EBADFD;
941
942 flags &= O_ACCMODE_STRICT;
943
944 if (flags == mode)
945 return 1;
946
947 if (flags == O_RDWR)
948 return 0;
949
950 return -EPROTOTYPE;
951 }
952
953 int fd_is_writable(int fd) {
954 int r;
955
956 assert(fd >= 0);
957
958 r = fd_vet_accmode(fd, O_WRONLY);
959 if (r >= 0)
960 return true;
961
962 if (IN_SET(r, -EPROTOTYPE, -EBADFD, -EISDIR))
963 return false;
964
965 return r;
966 }
967
968 int fd_verify_safe_flags_full(int fd, int extra_flags) {
969 int flags, unexpected_flags;
970
971 /* Check if an extrinsic fd is safe to work on (by a privileged service). This ensures that clients
972 * can't trick a privileged service into giving access to a file the client doesn't already have
973 * access to (especially via something like O_PATH).
974 *
975 * O_NOFOLLOW: For some reason the kernel will return this flag from fcntl(); it doesn't go away
976 * immediately after open(). It should have no effect whatsoever to an already-opened FD,
977 * and since we refuse O_PATH it should be safe.
978 *
979 * RAW_O_LARGEFILE: glibc secretly sets this and neglects to hide it from us if we call fcntl.
980 * See comment in src/basic/include/fcntl.h for more details about this.
981 *
982 * If 'extra_flags' is specified as non-zero the included flags are also allowed.
983 */
984
985 assert(fd >= 0);
986
987 flags = fcntl(fd, F_GETFL);
988 if (flags < 0)
989 return -errno;
990
991 unexpected_flags = flags & ~(O_ACCMODE_STRICT|O_NOFOLLOW|RAW_O_LARGEFILE|extra_flags);
992 if (unexpected_flags != 0)
993 return log_debug_errno(SYNTHETIC_ERRNO(EREMOTEIO),
994 "Unexpected flags set for extrinsic fd: 0%o",
995 (unsigned) unexpected_flags);
996
997 return flags & (O_ACCMODE_STRICT | extra_flags); /* return the flags variable, but remove the noise */
998 }
999
1000 unsigned read_nr_open(void) {
1001 _cleanup_free_ char *nr_open = NULL;
1002 int r;
1003
1004 /* Returns the kernel's current fd limit, either by reading it of /proc/sys if that works, or using the
1005 * hard-coded default compiled-in value of current kernels (1M) if not. This call will never fail. */
1006
1007 r = read_one_line_file("/proc/sys/fs/nr_open", &nr_open);
1008 if (r < 0)
1009 log_debug_errno(r, "Failed to read /proc/sys/fs/nr_open, ignoring: %m");
1010 else {
1011 unsigned v;
1012
1013 r = safe_atou(nr_open, &v);
1014 if (r < 0)
1015 log_debug_errno(r, "Failed to parse /proc/sys/fs/nr_open value '%s', ignoring: %m", nr_open);
1016 else
1017 return v;
1018 }
1019
1020 /* If we fail, fall back to the hard-coded kernel limit of 1024 * 1024. */
1021 return NR_OPEN_DEFAULT;
1022 }
1023
1024 int fd_get_diskseq(int fd, uint64_t *ret) {
1025 uint64_t diskseq;
1026
1027 assert(fd >= 0);
1028 assert(ret);
1029
1030 if (ioctl(fd, BLKGETDISKSEQ, &diskseq) < 0) {
1031 /* Note that the kernel is weird: non-existing ioctls currently return EINVAL
1032 * rather than ENOTTY on loopback block devices. They should fix that in the kernel,
1033 * but in the meantime we accept both here. */
1034 if (!ERRNO_IS_NOT_SUPPORTED(errno) && errno != EINVAL)
1035 return -errno;
1036
1037 return -EOPNOTSUPP;
1038 }
1039
1040 *ret = diskseq;
1041
1042 return 0;
1043 }
1044
1045 static bool is_literal_root(const char *p) {
1046 if (!p)
1047 return false;
1048
1049 /* Check if string consists of at least one '/', and possibly more, but nothing else */
1050 size_t n = strspn(p, "/");
1051 return n >= 1 && p[n] == 0;
1052 }
1053
1054 int path_is_root_at(int dir_fd, const char *path) {
1055 assert(wildcard_fd_is_valid(dir_fd));
1056
1057 if (dir_fd == XAT_FDROOT && isempty(path))
1058 return true;
1059
1060 if (IN_SET(dir_fd, XAT_FDROOT, AT_FDCWD) && is_literal_root(path))
1061 return true;
1062
1063 _cleanup_close_ int fd = -EBADF;
1064 if (!isempty(path)) {
1065 fd = xopenat(dir_fd, path, O_PATH|O_DIRECTORY|O_CLOEXEC);
1066 if (fd == -ENOTDIR)
1067 return false; /* the root dir must be a dir */
1068 if (fd < 0)
1069 return fd;
1070
1071 dir_fd = fd;
1072 }
1073
1074 /* Even if the root directory has the same inode as our fd, the fd may not point to the root
1075 * directory "/", and we also need to check that the mount ids are the same. Otherwise, a construct
1076 * like the following could be used to trick us:
1077 *
1078 * $ mkdir /tmp/x
1079 * $ mount --bind / /tmp/x
1080 */
1081
1082 return fds_inode_and_mount_same(dir_fd, XAT_FDROOT);
1083 }
1084
1085 int fds_inode_and_mount_same(int fd1, int fd2) {
1086 struct statx sx1, sx2;
1087 int r;
1088
1089 assert(wildcard_fd_is_valid(fd1));
1090 assert(wildcard_fd_is_valid(fd2));
1091
1092 r = xstatx(fd1, /* path = */ NULL, AT_EMPTY_PATH,
1093 STATX_TYPE|STATX_INO|STATX_MNT_ID,
1094 &sx1);
1095 if (r < 0)
1096 return r;
1097
1098 if (fd1 == fd2) /* Shortcut things if fds are the same (only after validating the fd) */
1099 return true;
1100
1101 r = xstatx(fd2, /* path = */ NULL, AT_EMPTY_PATH,
1102 STATX_TYPE|STATX_INO|STATX_MNT_ID,
1103 &sx2);
1104 if (r < 0)
1105 return r;
1106
1107 r = statx_mount_same(&sx1, &sx2);
1108 if (r <= 0)
1109 return r;
1110
1111 return statx_inode_same(&sx1, &sx2);
1112 }
1113
1114 int resolve_xat_fdroot(int *fd, const char **path, char **ret_buffer) {
1115 assert(fd);
1116 assert(path);
1117 assert(ret_buffer);
1118
1119 if (*fd != XAT_FDROOT) {
1120 *ret_buffer = NULL;
1121 return 0;
1122 }
1123
1124 if (isempty(*path)) {
1125 *path = "/";
1126 *ret_buffer = NULL;
1127 } else if (!path_is_absolute(*path)) {
1128 char *p = strjoin("/", *path);
1129 if (!p)
1130 return -ENOMEM;
1131
1132 *path = *ret_buffer = p;
1133 }
1134
1135 *fd = AT_FDCWD;
1136
1137 return 1;
1138 }
1139
1140 char* format_proc_fd_path(char buf[static PROC_FD_PATH_MAX], int fd) {
1141 assert(buf);
1142 assert(fd >= 0);
1143 assert_se(snprintf_ok(buf, PROC_FD_PATH_MAX, "/proc/self/fd/%i", fd));
1144 return buf;
1145 }
1146
1147 const char* accmode_to_string(int flags) {
1148 switch (flags & O_ACCMODE_STRICT) {
1149 case O_RDONLY:
1150 return "ro";
1151 case O_WRONLY:
1152 return "wo";
1153 case O_RDWR:
1154 return "rw";
1155 default:
1156 return NULL;
1157 }
1158 }
1159
1160 char* format_proc_pid_fd_path(char buf[static PROC_PID_FD_PATH_MAX], pid_t pid, int fd) {
1161 assert(buf);
1162 assert(fd >= 0);
1163 assert(pid >= 0);
1164 assert_se(snprintf_ok(buf, PROC_PID_FD_PATH_MAX, "/proc/" PID_FMT "/fd/%i", pid == 0 ? getpid_cached() : pid, fd));
1165 return buf;
1166 }
1167
1168 int proc_fd_enoent_errno(void) {
1169 int r;
1170
1171 /* When ENOENT is returned during the use of FORMAT_PROC_FD_PATH, it can mean two things:
1172 * that the fd does not exist or that /proc/ is not mounted.
1173 * Let's make things debuggable and figure out the most appropriate errno. */
1174
1175 r = proc_mounted();
1176 if (r == 0)
1177 return -ENOSYS; /* /proc/ is not available or not set up properly, we're most likely
1178 in some chroot environment. */
1179 if (r > 0)
1180 return -EBADF; /* If /proc/ is definitely around then this means the fd is not valid. */
1181
1182 return -ENOENT; /* Otherwise let's propagate the original ENOENT. */
1183 }