• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 20012523220

07 Dec 2025 11:33PM UTC coverage: 72.656% (+0.1%) from 72.546%
20012523220

push

github

yuwata
import: include unistd.h for pipe2

This is needed for e.g. pipe2 and unlinkat and a build failure
is reproducible when libarchive support is disabled.

309255 of 425645 relevant lines covered (72.66%)

1123501.7 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.42
/src/basic/fd-util.c
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 "mountpoint-util.h"
20
#include "parse-util.h"
21
#include "path-util.h"
22
#include "process-util.h"
23
#include "sort-util.h"
24
#include "stat-util.h"
25
#include "stdio-util.h"
26
#include "string-util.h"
27

28
/* The maximum number of iterations in the loop to close descriptors in the fallback case
29
 * when /proc/self/fd/ is inaccessible. */
30
#define MAX_FD_LOOP_LIMIT (1024*1024)
31

32
int close_nointr(int fd) {
40,779,959✔
33
        assert(fd >= 0);
40,779,959✔
34

35
        if (close(fd) >= 0)
40,779,959✔
36
                return 0;
37

38
        /*
39
         * Just ignore EINTR; a retry loop is the wrong thing to do on
40
         * Linux.
41
         *
42
         * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
43
         * https://bugzilla.gnome.org/show_bug.cgi?id=682819
44
         * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
45
         * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
46
         */
47
        if (errno == EINTR)
9,762✔
48
                return 0;
49

50
        return -errno;
9,762✔
51
}
52

53
int safe_close(int fd) {
108,300,435✔
54
        /*
55
         * Like close_nointr() but cannot fail. Guarantees errno is unchanged. Is a noop for negative fds,
56
         * and returns -EBADF, so that it can be used in this syntax:
57
         *
58
         * fd = safe_close(fd);
59
         */
60

61
        if (fd >= 0) {
108,300,435✔
62
                PROTECT_ERRNO;
×
63

64
                /* The kernel might return pretty much any error code
65
                 * via close(), but the fd will be closed anyway. The
66
                 * only condition we want to check for here is whether
67
                 * the fd was invalid at all... */
68

69
                assert_se(close_nointr(fd) != -EBADF);
40,351,518✔
70
        }
71

72
        return -EBADF;
108,300,435✔
73
}
74

75
void safe_close_pair(int p[static 2]) {
576,993✔
76
        assert(p);
576,993✔
77

78
        if (p[0] == p[1]) {
576,993✔
79
                /* Special case pairs which use the same fd in both
80
                 * directions... */
81
                p[0] = p[1] = safe_close(p[0]);
537,965✔
82
                return;
537,965✔
83
        }
84

85
        p[0] = safe_close(p[0]);
39,028✔
86
        p[1] = safe_close(p[1]);
39,028✔
87
}
88

89
void close_many(const int fds[], size_t n_fds) {
3,412,155✔
90
        assert(fds || n_fds == 0);
3,412,155✔
91

92
        FOREACH_ARRAY(fd, fds, n_fds)
3,467,783✔
93
                safe_close(*fd);
55,628✔
94
}
3,412,155✔
95

96
void close_many_unset(int fds[], size_t n_fds) {
32✔
97
        assert(fds || n_fds == 0);
32✔
98

99
        FOREACH_ARRAY(fd, fds, n_fds)
33✔
100
                *fd = safe_close(*fd);
1✔
101
}
32✔
102

103
void close_many_and_free(int *fds, size_t n_fds) {
736✔
104
        assert(fds || n_fds == 0);
736✔
105

106
        close_many(fds, n_fds);
736✔
107
        free(fds);
736✔
108
}
736✔
109

110
int fclose_nointr(FILE *f) {
2,050,617✔
111
        assert(f);
2,050,617✔
112

113
        /* Same as close_nointr(), but for fclose() */
114

115
        errno = 0; /* Extra safety: if the FILE* object is not encapsulating an fd, it might not set errno
2,050,617✔
116
                    * correctly. Let's hence initialize it to zero first, so that we aren't confused by any
117
                    * prior errno here */
118
        if (fclose(f) == 0)
2,050,617✔
119
                return 0;
120

121
        if (errno == EINTR)
×
122
                return 0;
123

124
        return errno_or_else(EIO);
×
125
}
126

127
FILE* safe_fclose(FILE *f) {
3,892,311✔
128

129
        /* Same as safe_close(), but for fclose() */
130

131
        if (f) {
3,892,311✔
132
                PROTECT_ERRNO;
×
133

134
                assert_se(fclose_nointr(f) != -EBADF);
2,050,617✔
135
        }
136

137
        return NULL;
3,892,311✔
138
}
139

140
DIR* safe_closedir(DIR *d) {
×
141

142
        if (d) {
×
143
                PROTECT_ERRNO;
×
144

145
                assert_se(closedir(d) >= 0 || errno != EBADF);
×
146
        }
147

148
        return NULL;
×
149
}
150

151
int fd_nonblock(int fd, bool nonblock) {
1,854,501✔
152
        int flags, nflags;
1,854,501✔
153

154
        assert(fd >= 0);
1,854,501✔
155

156
        flags = fcntl(fd, F_GETFL, 0);
1,854,501✔
157
        if (flags < 0)
1,854,501✔
158
                return -errno;
×
159

160
        nflags = UPDATE_FLAG(flags, O_NONBLOCK, nonblock);
1,854,501✔
161
        if (nflags == flags)
1,854,501✔
162
                return 0;
163

164
        if (fcntl(fd, F_SETFL, nflags) < 0)
1,830,975✔
165
                return -errno;
×
166

167
        return 1;
168
}
169

170
int stdio_disable_nonblock(void) {
15,858✔
171
        int ret = 0;
15,858✔
172

173
        /* stdin/stdout/stderr really should have O_NONBLOCK, which would confuse apps if left on, as
174
         * write()s might unexpectedly fail with EAGAIN. */
175

176
        RET_GATHER(ret, fd_nonblock(STDIN_FILENO, false));
15,858✔
177
        RET_GATHER(ret, fd_nonblock(STDOUT_FILENO, false));
15,858✔
178
        RET_GATHER(ret, fd_nonblock(STDERR_FILENO, false));
15,858✔
179

180
        return ret;
15,858✔
181
}
182

183
int fd_cloexec(int fd, bool cloexec) {
78,012✔
184
        int flags, nflags;
78,012✔
185

186
        assert(fd >= 0);
78,012✔
187

188
        flags = fcntl(fd, F_GETFD, 0);
78,012✔
189
        if (flags < 0)
78,012✔
190
                return -errno;
×
191

192
        nflags = UPDATE_FLAG(flags, FD_CLOEXEC, cloexec);
78,012✔
193
        if (nflags == flags)
78,012✔
194
                return 0;
195

196
        return RET_NERRNO(fcntl(fd, F_SETFD, nflags));
66,582✔
197
}
198

199
int fd_cloexec_many(const int fds[], size_t n_fds, bool cloexec) {
111✔
200
        int r = 0;
111✔
201

202
        assert(fds || n_fds == 0);
111✔
203

204
        FOREACH_ARRAY(fd, fds, n_fds) {
143✔
205
                if (*fd < 0) /* Skip gracefully over already invalidated fds */
32✔
206
                        continue;
×
207

208
                RET_GATHER(r, fd_cloexec(*fd, cloexec));
32✔
209
        }
210

211
        return r;
111✔
212
}
213

214
static bool fd_in_set(int fd, const int fds[], size_t n_fds) {
26,253✔
215
        assert(fd >= 0);
26,253✔
216
        assert(fds || n_fds == 0);
26,253✔
217

218
        FOREACH_ARRAY(i, fds, n_fds) {
14,067,166✔
219
                if (*i < 0)
14,043,147✔
220
                        continue;
×
221

222
                if (*i == fd)
14,043,147✔
223
                        return true;
224
        }
225

226
        return false;
227
}
228

229
int get_max_fd(void) {
7✔
230
        struct rlimit rl;
7✔
231
        rlim_t m;
7✔
232

233
        /* Return the highest possible fd, based RLIMIT_NOFILE, but enforcing FD_SETSIZE-1 as lower boundary
234
         * and INT_MAX as upper boundary. */
235

236
        if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
7✔
237
                return -errno;
×
238

239
        m = MAX(rl.rlim_cur, rl.rlim_max);
7✔
240
        if (m < FD_SETSIZE) /* Let's always cover at least 1024 fds */
7✔
241
                return FD_SETSIZE-1;
242

243
        if (m == RLIM_INFINITY || m > INT_MAX) /* Saturate on overflow. After all fds are "int", hence can
7✔
244
                                                * never be above INT_MAX */
245
                return INT_MAX;
246

247
        return (int) (m - 1);
7✔
248
}
249

250
int close_all_fds_frugal(const int except[], size_t n_except) {
3✔
251
        int max_fd, r = 0;
3✔
252

253
        assert(except || n_except == 0);
3✔
254

255
        /* This is the inner fallback core of close_all_fds(). This never calls malloc() or opendir() or so
256
         * and hence is safe to be called in signal handler context. Most users should call close_all_fds(),
257
         * but when we assume we are called from signal handler context, then use this simpler call
258
         * instead. */
259

260
        max_fd = get_max_fd();
3✔
261
        if (max_fd < 0)
3✔
262
                return max_fd;
3✔
263

264
        /* Refuse to do the loop over more too many elements. It's better to fail immediately than to
265
         * spin the CPU for a long time. */
266
        if (max_fd > MAX_FD_LOOP_LIMIT)
3✔
267
                return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
×
268
                                       "Refusing to loop over %d potential fds.", max_fd);
269

270
        for (int fd = 3; fd >= 0; fd = fd < max_fd ? fd + 1 : -EBADF) {
20,994✔
271
                int q;
20,991✔
272

273
                if (fd_in_set(fd, except, n_except))
20,991✔
274
                        continue;
1,972✔
275

276
                q = close_nointr(fd);
19,019✔
277
                if (q != -EBADF)
19,019✔
278
                        RET_GATHER(r, q);
9,258✔
279
        }
280

281
        return r;
282
}
283

284
int close_all_fds_by_proc(const int except[], size_t n_except) {
2✔
285
        _cleanup_closedir_ DIR *d = NULL;
2✔
286
        int r = 0;
2✔
287

288
        d = opendir("/proc/self/fd");
2✔
289
        if (!d)
2✔
290
                return close_all_fds_frugal(except, n_except); /* ultimate fallback if /proc/ is not available */
×
291

292
        FOREACH_DIRENT(de, d, return -errno) {
5,276✔
293
                int fd = -EBADF, q;
5,270✔
294

295
                if (!IN_SET(de->d_type, DT_LNK, DT_UNKNOWN))
5,270✔
296
                        continue;
×
297

298
                fd = parse_fd(de->d_name);
5,270✔
299
                if (fd < 0)
5,270✔
300
                        /* Let's better ignore this, just in case */
301
                        continue;
×
302

303
                if (fd < 3)
5,270✔
304
                        continue;
6✔
305

306
                if (fd == dirfd(d))
5,264✔
307
                        continue;
2✔
308

309
                if (fd_in_set(fd, except, n_except))
5,262✔
310
                        continue;
262✔
311

312
                q = close_nointr(fd);
5,000✔
313
                if (q != -EBADF) /* Valgrind has its own FD and doesn't want to have it closed */
5,000✔
314
                        RET_GATHER(r, q);
5,000✔
315
        }
316

317
        return r;
318
}
319

320
static bool have_close_range = true; /* Assume we live in the future */
321

322
static int close_all_fds_special_case(const int except[], size_t n_except) {
44,143✔
323
        assert(n_except == 0 || except);
44,143✔
324

325
        /* Handles a few common special cases separately, since they are common and can be optimized really
326
         * nicely, since we won't need sorting for them. Returns > 0 if the special casing worked, 0
327
         * otherwise. */
328

329
        if (!have_close_range)
44,143✔
330
                return 0;
331

332
        if (n_except == 1 && except[0] < 0) /* Minor optimization: if we only got one fd, and it's invalid,
44,143✔
333
                                             * we got none */
334
                n_except = 0;
335

336
        switch (n_except) {
44,143✔
337

338
        case 0:
8,586✔
339
                /* Close everything. Yay! */
340

341
                if (close_range(3, INT_MAX, 0) >= 0)
8,586✔
342
                        return 1;
343

344
                if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) {
×
345
                        have_close_range = false;
×
346
                        return 0;
×
347
                }
348

349
                return -errno;
×
350

351
        case 1:
15,625✔
352
                /* Close all but exactly one, then we don't need no sorting. This is a pretty common
353
                 * case, hence let's handle it specially. */
354

355
                if ((except[0] <= 3 || close_range(3, except[0]-1, 0) >= 0) &&
15,625✔
356
                    (except[0] >= INT_MAX || close_range(MAX(3, except[0]+1), -1, 0) >= 0))
15,625✔
357
                        return 1;
15,625✔
358

359
                if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) {
×
360
                        have_close_range = false;
×
361
                        return 0;
×
362
                }
363

364
                return -errno;
×
365

366
        default:
367
                return 0;
368
        }
369
}
370

371
int close_all_fds_without_malloc(const int except[], size_t n_except) {
2✔
372
        int r;
2✔
373

374
        assert(n_except == 0 || except);
2✔
375

376
        r = close_all_fds_special_case(except, n_except);
2✔
377
        if (r < 0)
2✔
378
                return r;
379
        if (r > 0) /* special case worked! */
2✔
380
                return 0;
381

382
        return close_all_fds_frugal(except, n_except);
1✔
383
}
384

385
int close_all_fds(const int except[], size_t n_except) {
44,141✔
386
        int r;
44,141✔
387

388
        assert(n_except == 0 || except);
44,141✔
389

390
        r = close_all_fds_special_case(except, n_except);
44,141✔
391
        if (r < 0)
44,141✔
392
                return r;
44,141✔
393
        if (r > 0) /* special case worked! */
44,141✔
394
                return 0;
395

396
        if (!have_close_range)
19,931✔
397
                return close_all_fds_by_proc(except, n_except);
×
398

399
        _cleanup_free_ int *sorted_malloc = NULL;
19,931✔
400
        size_t n_sorted;
19,931✔
401
        int *sorted;
19,931✔
402

403
        /* In the best case we have close_range() to close all fds between a start and an end fd, which we
404
         * can use on the "inverted" exception array, i.e. all intervals between all adjacent pairs from the
405
         * sorted exception array. This changes loop complexity from O(n) where n is number of open fds to
406
         * O(m⋅log(m)) where m is the number of fds to keep open. Given that we assume n ≫ m that's
407
         * preferable to us. */
408

409
        assert(n_except < SIZE_MAX);
19,931✔
410
        n_sorted = n_except + 1;
19,931✔
411

412
        if (n_sorted > ALLOCA_MAX / sizeof(int)) /* Use heap for large numbers of fds, stack otherwise */
19,931✔
413
                sorted = sorted_malloc = new(int, n_sorted);
×
414
        else
415
                sorted = newa(int, n_sorted);
19,931✔
416

417
        if (!sorted) /* Fallback on OOM. */
19,931✔
418
                return close_all_fds_by_proc(except, n_except);
×
419

420
        memcpy(sorted, except, n_except * sizeof(int));
19,931✔
421

422
        /* Let's add fd 2 to the list of fds, to simplify the loop below, as this
423
         * allows us to cover the head of the array the same way as the body */
424
        sorted[n_sorted-1] = 2;
19,931✔
425

426
        typesafe_qsort(sorted, n_sorted, cmp_int);
19,931✔
427

428
        for (size_t i = 0; i < n_sorted-1; i++) {
89,091✔
429
                int start, end;
69,160✔
430

431
                start = MAX(sorted[i], 2); /* The first three fds shall always remain open */
69,160✔
432
                end = MAX(sorted[i+1], 2);
69,160✔
433

434
                assert(end >= start);
69,160✔
435

436
                if (end - start <= 1)
69,160✔
437
                        continue;
26,487✔
438

439
                /* Close everything between the start and end fds (both of which shall stay open) */
440
                if (close_range(start + 1, end - 1, 0) < 0) {
42,673✔
441
                        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
×
442
                                return -errno;
×
443

444
                        have_close_range = false;
×
445
                        return close_all_fds_by_proc(except, n_except);
×
446
                }
447
        }
448

449
        /* The loop succeeded. Let's now close everything beyond the end */
450

451
        if (sorted[n_sorted-1] >= INT_MAX) /* Dont let the addition below overflow */
19,931✔
452
                return 0;
453

454
        if (close_range(sorted[n_sorted-1] + 1, INT_MAX, 0) < 0) {
19,931✔
455
                if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
×
456
                        return -errno;
×
457

458
                have_close_range = false;
×
459
                return close_all_fds_by_proc(except, n_except);
×
460
        }
461

462
        return 0;
463
}
464

465
int pack_fds(int fds[], size_t n_fds) {
9,994✔
466
        if (n_fds <= 0)
9,994✔
467
                return 0;
468

469
        /* Shifts around the fds in the provided array such that they
470
         * all end up packed next to each-other, in order, starting
471
         * from SD_LISTEN_FDS_START. This must be called after close_all_fds();
472
         * it is likely to freeze up otherwise. You should probably use safe_fork_full
473
         * with FORK_CLOSE_ALL_FDS|FORK_PACK_FDS set, to ensure that this is done correctly.
474
         * The fds array is modified in place with the new FD numbers. */
475

476
        assert(fds);
1,724✔
477

478
        for (int start = 0;;) {
479
                int restart_from = -1;
1,724✔
480

481
                for (int i = start; i < (int) n_fds; i++) {
5,365✔
482
                        int nfd;
3,641✔
483

484
                        /* Already at right index? */
485
                        if (fds[i] == i + 3)
3,641✔
486
                                continue;
3✔
487

488
                        nfd = fcntl(fds[i], F_DUPFD, i + 3);
3,638✔
489
                        if (nfd < 0)
3,638✔
490
                                return -errno;
×
491

492
                        safe_close(fds[i]);
3,638✔
493
                        fds[i] = nfd;
3,638✔
494

495
                        /* Hmm, the fd we wanted isn't free? Then
496
                         * let's remember that and try again from here */
497
                        if (nfd != i + 3 && restart_from < 0)
3,638✔
498
                                restart_from = i;
×
499
                }
500

501
                if (restart_from < 0)
1,724✔
502
                        break;
503

504
                start = restart_from;
505
        }
506

507
        assert(fds[0] == 3);
1,724✔
508

509
        return 0;
510
}
511

512
int fd_validate(int fd) {
94,078✔
513
        if (fd < 0)
94,078✔
514
                return -EBADF;
515

516
        if (fcntl(fd, F_GETFD) < 0)
94,076✔
517
                return -errno;
37,312✔
518

519
        return 0;
520
}
521

522
int same_fd(int a, int b) {
14,071✔
523
        struct stat sta, stb;
14,071✔
524
        pid_t pid;
14,071✔
525
        int r, fa, fb;
14,071✔
526

527
        assert(a >= 0);
14,071✔
528
        assert(b >= 0);
14,071✔
529

530
        /* Compares two file descriptors. Note that semantics are quite different depending on whether we
531
         * have F_DUPFD_QUERY/kcmp() or we don't. If we have F_DUPFD_QUERY/kcmp() this will only return true
532
         * for dup()ed file descriptors, but not otherwise. If we don't have F_DUPFD_QUERY/kcmp() this will
533
         * also return true for two fds of the same file, created by separate open() calls. Since we use this
534
         * call mostly for filtering out duplicates in the fd store this difference hopefully doesn't matter
535
         * too much.
536
         *
537
         * Guarantees that if either of the passed fds is not allocated we'll return -EBADF. */
538

539
        if (a == b) {
14,071✔
540
                /* Let's validate that the fd is valid */
541
                r = fd_validate(a);
7✔
542
                if (r < 0)
7✔
543
                        return r;
14,071✔
544

545
                return true;
6✔
546
        }
547

548
        /* Try to use F_DUPFD_QUERY if we have it first, as it is the nicest API */
549
        r = fcntl(a, F_DUPFD_QUERY, b);
14,064✔
550
        if (r > 0)
14,064✔
551
                return true;
552
        if (r == 0) {
14,056✔
553
                /* 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. */
554
                r = fd_validate(b);
14,055✔
555
                if (r < 0)
14,055✔
556
                        return r;
557

558
                return false;
14,054✔
559
        }
560
        /* 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. */
561
        if (errno == EBADF) {
1✔
562
                /* EBADF could mean two things: the first fd is not valid, or it is valid and is O_PATH and
563
                 * F_DUPFD_QUERY is not supported. Let's validate the fd explicitly, to distinguish this
564
                 * case. */
565
                r = fd_validate(a);
1✔
566
                if (r < 0)
1✔
567
                        return r;
568

569
                /* If the fd is valid, but we got EBADF, then let's try kcmp(). */
570
        } else if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno) && errno != EINVAL)
×
571
                return -errno;
×
572

573
        /* Try to use kcmp() if we have it. */
574
        pid = getpid_cached();
×
575
        r = kcmp(pid, pid, KCMP_FILE, a, b);
×
576
        if (r >= 0)
×
577
                return !r;
×
578
        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
×
579
                return -errno;
×
580

581
        /* We have neither F_DUPFD_QUERY nor kcmp(), use fstat() instead. */
582
        if (fstat(a, &sta) < 0)
×
583
                return -errno;
×
584

585
        if (fstat(b, &stb) < 0)
×
586
                return -errno;
×
587

588
        if (!stat_inode_same(&sta, &stb))
×
589
                return false;
590

591
        /* We consider all device fds different, since two device fds might refer to quite different device
592
         * contexts even though they share the same inode and backing dev_t. */
593

594
        if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
×
595
                return false;
596

597
        /* The fds refer to the same inode on disk, let's also check if they have the same fd flags. This is
598
         * useful to distinguish the read and write side of a pipe created with pipe(). */
599
        fa = fcntl(a, F_GETFL);
×
600
        if (fa < 0)
×
601
                return -errno;
×
602

603
        fb = fcntl(b, F_GETFL);
×
604
        if (fb < 0)
×
605
                return -errno;
×
606

607
        return fa == fb;
×
608
}
609

610
bool fdname_is_valid(const char *s) {
16,003✔
611
        const char *p;
16,003✔
612

613
        /* Validates a name for $LISTEN_FDNAMES. We basically allow
614
         * everything ASCII that's not a control character. Also, as
615
         * special exception the ":" character is not allowed, as we
616
         * use that as field separator in $LISTEN_FDNAMES.
617
         *
618
         * Note that the empty string is explicitly allowed
619
         * here. However, we limit the length of the names to 255
620
         * characters. */
621

622
        if (!s)
16,003✔
623
                return false;
624

625
        for (p = s; *p; p++) {
239,697✔
626
                if (*p < ' ')
223,699✔
627
                        return false;
628
                if (*p >= 127)
223,699✔
629
                        return false;
630
                if (*p == ':')
223,699✔
631
                        return false;
632
        }
633

634
        return p - s <= FDNAME_MAX;
15,998✔
635
}
636

637
int fd_get_path(int fd, char **ret) {
3,597,430✔
638
        int r;
3,597,430✔
639

640
        assert(fd >= 0 || fd == AT_FDCWD);
3,597,430✔
641

642
        if (fd == AT_FDCWD)
3,597,430✔
643
                return safe_getcwd(ret);
5,105✔
644

645
        r = readlink_malloc(FORMAT_PROC_FD_PATH(fd), ret);
3,592,325✔
646
        if (r == -ENOENT)
3,592,325✔
647
                return proc_fd_enoent_errno();
4✔
648
        return r;
649
}
650

651
int move_fd(int from, int to, int cloexec) {
18,658✔
652
        int r;
18,658✔
653

654
        /* Move fd 'from' to 'to', make sure FD_CLOEXEC remains equal if requested, and release the old fd. If
655
         * 'cloexec' is passed as -1, the original FD_CLOEXEC is inherited for the new fd. If it is 0, it is turned
656
         * off, if it is > 0 it is turned on. */
657

658
        if (from < 0)
18,658✔
659
                return -EBADF;
660
        if (to < 0)
18,658✔
661
                return -EBADF;
662

663
        if (from == to) {
18,658✔
664

665
                if (cloexec >= 0) {
×
666
                        r = fd_cloexec(to, cloexec);
×
667
                        if (r < 0)
×
668
                                return r;
669
                }
670

671
                return to;
×
672
        }
673

674
        if (cloexec < 0) {
18,658✔
675
                int fl;
×
676

677
                fl = fcntl(from, F_GETFD, 0);
×
678
                if (fl < 0)
×
679
                        return -errno;
×
680

681
                cloexec = FLAGS_SET(fl, FD_CLOEXEC);
×
682
        }
683

684
        r = dup3(from, to, cloexec ? O_CLOEXEC : 0);
37,316✔
685
        if (r < 0)
18,658✔
686
                return -errno;
×
687

688
        assert(r == to);
18,658✔
689

690
        safe_close(from);
18,658✔
691

692
        return to;
18,658✔
693
}
694

695
int fd_move_above_stdio(int fd) {
751,822✔
696
        int flags, copy;
751,822✔
697
        PROTECT_ERRNO;
751,822✔
698

699
        /* Moves the specified file descriptor if possible out of the range [0…2], i.e. the range of
700
         * stdin/stdout/stderr. If it can't be moved outside of this range the original file descriptor is
701
         * returned. This call is supposed to be used for long-lasting file descriptors we allocate in our code that
702
         * might get loaded into foreign code, and where we want ensure our fds are unlikely used accidentally as
703
         * stdin/stdout/stderr of unrelated code.
704
         *
705
         * Note that this doesn't fix any real bugs, it just makes it less likely that our code will be affected by
706
         * buggy code from others that mindlessly invokes 'fprintf(stderr, …' or similar in places where stderr has
707
         * been closed before.
708
         *
709
         * This function is written in a "best-effort" and "least-impact" style. This means whenever we encounter an
710
         * error we simply return the original file descriptor, and we do not touch errno. */
711

712
        if (fd < 0 || fd > 2)
751,822✔
713
                return fd;
714

715
        flags = fcntl(fd, F_GETFD, 0);
129✔
716
        if (flags < 0)
129✔
717
                return fd;
718

719
        if (flags & FD_CLOEXEC)
129✔
720
                copy = fcntl(fd, F_DUPFD_CLOEXEC, 3);
115✔
721
        else
722
                copy = fcntl(fd, F_DUPFD, 3);
14✔
723
        if (copy < 0)
129✔
724
                return fd;
725

726
        assert(copy > 2);
129✔
727

728
        (void) close(fd);
129✔
729
        return copy;
730
}
731

732
int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd) {
16,168✔
733
        int fd[3] = { original_input_fd,             /* Put together an array of fds we work on */
16,168✔
734
                      original_output_fd,
735
                      original_error_fd },
736
            null_fd = -EBADF,                        /* If we open /dev/null, we store the fd to it here */
16,168✔
737
            copy_fd[3] = EBADF_TRIPLET,              /* This contains all fds we duplicate here
16,168✔
738
                                                      * temporarily, and hence need to close at the end. */
739
            r;
740
        bool null_readable, null_writable;
16,168✔
741

742
        /* Sets up stdin, stdout, stderr with the three file descriptors passed in. If any of the descriptors
743
         * is specified as -EBADF it will be connected with /dev/null instead. If any of the file descriptors
744
         * is passed as itself (e.g. stdin as STDIN_FILENO) it is left unmodified, but the O_CLOEXEC bit is
745
         * turned off should it be on.
746
         *
747
         * Note that if any of the passed file descriptors are > 2 they will be closed — both on success and
748
         * on failure! Thus, callers should assume that when this function returns the input fds are
749
         * invalidated.
750
         *
751
         * Note that when this function fails stdin/stdout/stderr might remain half set up!
752
         *
753
         * O_CLOEXEC is turned off for all three file descriptors (which is how it should be for
754
         * stdin/stdout/stderr). */
755

756
        null_readable = original_input_fd < 0;
16,168✔
757
        null_writable = original_output_fd < 0 || original_error_fd < 0;
16,168✔
758

759
        /* First step, open /dev/null once, if we need it */
760
        if (null_readable || null_writable) {
16,168✔
761

762
                /* Let's open this with O_CLOEXEC first, and convert it to non-O_CLOEXEC when we move the fd to the final position. */
763
                null_fd = open("/dev/null", (null_readable && null_writable ? O_RDWR :
27,019✔
764
                                             null_readable ? O_RDONLY : O_WRONLY) | O_CLOEXEC);
13,456✔
765
                if (null_fd < 0) {
13,563✔
766
                        r = -errno;
×
767
                        goto finish;
×
768
                }
769

770
                /* If this fd is in the 0…2 range, let's move it out of it */
771
                if (null_fd < 3) {
13,563✔
772
                        int copy;
13✔
773

774
                        copy = fcntl(null_fd, F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
13✔
775
                        if (copy < 0) {
13✔
776
                                r = -errno;
×
777
                                goto finish;
×
778
                        }
779

780
                        close_and_replace(null_fd, copy);
13✔
781
                }
782
        }
783

784
        /* Let's assemble fd[] with the fds to install in place of stdin/stdout/stderr */
785
        for (int i = 0; i < 3; i++)
64,672✔
786
                if (fd[i] < 0)
48,504✔
787
                        fd[i] = null_fd;        /* A negative parameter means: connect this one to /dev/null */
13,751✔
788
                else if (fd[i] != i && fd[i] < 3) {
34,753✔
789
                        /* 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. */
790
                        copy_fd[i] = fcntl(fd[i], F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
98✔
791
                        if (copy_fd[i] < 0) {
98✔
792
                                r = -errno;
×
793
                                goto finish;
×
794
                        }
795

796
                        fd[i] = copy_fd[i];
98✔
797
                }
798

799
        /* At this point we now have the fds to use in fd[], and they are all above the stdio range, so that
800
         * we have freedom to move them around. If the fds already were at the right places then the specific
801
         * fds are -EBADF. Let's now move them to the right places. This is the point of no return. */
802
        for (int i = 0; i < 3; i++)
64,672✔
803
                if (fd[i] == i) {
48,504✔
804
                        /* fd is already in place, but let's make sure O_CLOEXEC is off */
805
                        r = fd_cloexec(i, false);
5,026✔
806
                        if (r < 0)
5,026✔
807
                                goto finish;
×
808
                } else {
809
                        assert(fd[i] > 2);
43,478✔
810

811
                        if (dup2(fd[i], i) < 0) { /* Turns off O_CLOEXEC on the new fd. */
43,478✔
812
                                r = -errno;
×
813
                                goto finish;
×
814
                        }
815
                }
816

817
        r = 0;
818

819
finish:
16,168✔
820
        /* Close the original fds, but only if they were outside of the stdio range. Also, properly check for the same
821
         * fd passed in multiple times. */
822
        safe_close_above_stdio(original_input_fd);
16,168✔
823
        if (original_output_fd != original_input_fd)
16,168✔
824
                safe_close_above_stdio(original_output_fd);
15,887✔
825
        if (original_error_fd != original_input_fd && original_error_fd != original_output_fd)
16,168✔
826
                safe_close_above_stdio(original_error_fd);
15,724✔
827

828
        /* Close the copies we moved > 2 */
829
        close_many(copy_fd, 3);
16,168✔
830

831
        /* Close our null fd, if it's > 2 */
832
        safe_close_above_stdio(null_fd);
16,168✔
833

834
        return r;
16,168✔
835
}
836

837
int fd_reopen(int fd, int flags) {
1,462,599✔
838
        assert(fd >= 0 || fd == AT_FDCWD);
1,462,599✔
839
        assert(!FLAGS_SET(flags, O_CREAT));
1,462,599✔
840

841
        /* Reopens the specified fd with new flags. This is useful for convert an O_PATH fd into a regular one, or to
842
         * turn O_RDWR fds into O_RDONLY fds.
843
         *
844
         * This doesn't work on sockets (since they cannot be open()ed, ever).
845
         *
846
         * This implicitly resets the file read index to 0.
847
         *
848
         * If AT_FDCWD is specified as file descriptor gets an fd to the current cwd.
849
         *
850
         * If the specified file descriptor refers to a symlink via O_PATH, then this function cannot be used
851
         * to follow that symlink. Because we cannot have non-O_PATH fds to symlinks reopening it without
852
         * O_PATH will always result in -ELOOP. Or in other words: if you have an O_PATH fd to a symlink you
853
         * can reopen it only if you pass O_PATH again. */
854

855
        if (FLAGS_SET(flags, O_NOFOLLOW))
1,462,599✔
856
                /* O_NOFOLLOW is not allowed in fd_reopen(), because after all this is primarily implemented
857
                 * via a symlink-based interface in /proc/self/fd. Let's refuse this here early. Note that
858
                 * the kernel would generate ELOOP here too, hence this manual check is mostly redundant –
859
                 * the only reason we add it here is so that the O_DIRECTORY special case (see below) behaves
860
                 * the same way as the non-O_DIRECTORY case. */
861
                return -ELOOP;
1,462,599✔
862

863
        if (FLAGS_SET(flags, O_DIRECTORY) || fd == AT_FDCWD)
1,462,597✔
864
                /* If we shall reopen the fd as directory we can just go via "." and thus bypass the whole
865
                 * magic /proc/ directory, and make ourselves independent of that being mounted. */
866
                return RET_NERRNO(openat(fd, ".", flags | O_DIRECTORY));
222,178✔
867

868
        int new_fd = open(FORMAT_PROC_FD_PATH(fd), flags);
1,240,421✔
869
        if (new_fd < 0) {
1,240,421✔
870
                if (errno != ENOENT)
47,263✔
871
                        return -errno;
47,262✔
872

873
                return proc_fd_enoent_errno();
1✔
874
        }
875

876
        return new_fd;
877
}
878

879
int fd_reopen_propagate_append_and_position(int fd, int flags) {
38✔
880
        /* Invokes fd_reopen(fd, flags), but propagates O_APPEND if set on original fd, and also tries to
881
         * keep current file position.
882
         *
883
         * You should use this if the original fd potentially is O_APPEND, otherwise we get rather
884
         * "unexpected" behavior. Unless you intentionally want to overwrite pre-existing data, and have
885
         * your output overwritten by the next user.
886
         *
887
         * Use case: "systemd-run --pty >> some-log".
888
         *
889
         * The "keep position" part is obviously nonsense for the O_APPEND case, but should reduce surprises
890
         * if someone carefully pre-positioned the passed in original input or non-append output FDs. */
891

892
        assert(fd >= 0);
38✔
893
        assert(!(flags & (O_APPEND|O_DIRECTORY)));
38✔
894

895
        int existing_flags = fcntl(fd, F_GETFL);
38✔
896
        if (existing_flags < 0)
38✔
897
                return -errno;
×
898

899
        int new_fd = fd_reopen(fd, flags | (existing_flags & O_APPEND));
38✔
900
        if (new_fd < 0)
38✔
901
                return new_fd;
902

903
        /* Try to adjust the offset, but ignore errors. */
904
        off_t p = lseek(fd, 0, SEEK_CUR);
27✔
905
        if (p > 0) {
27✔
906
                off_t new_p = lseek(new_fd, p, SEEK_SET);
×
907
                if (new_p < 0)
×
908
                        log_debug_errno(errno,
×
909
                                        "Failed to propagate file position for re-opened fd %d, ignoring: %m",
910
                                        fd);
911
                else if (new_p != p)
×
912
                        log_debug("Failed to propagate file position for re-opened fd %d (%lld != %lld), ignoring.",
×
913
                                  fd, (long long) new_p, (long long) p);
914
        }
915

916
        return new_fd;
917
}
918

919
int fd_reopen_condition(
1,239,680✔
920
                int fd,
921
                int flags,
922
                int mask,
923
                int *ret_new_fd) {
924

925
        int r, new_fd;
1,239,680✔
926

927
        assert(fd >= 0);
1,239,680✔
928
        assert(!FLAGS_SET(flags, O_CREAT));
1,239,680✔
929

930
        /* Invokes fd_reopen(fd, flags), but only if the existing F_GETFL flags don't match the specified
931
         * flags (masked by the specified mask). This is useful for converting O_PATH fds into real fds if
932
         * needed, but only then. */
933

934
        r = fcntl(fd, F_GETFL);
1,239,680✔
935
        if (r < 0)
1,239,680✔
936
                return -errno;
×
937

938
        if ((r & mask) == (flags & mask)) {
1,239,680✔
939
                *ret_new_fd = -EBADF;
1,234,070✔
940
                return fd;
1,234,070✔
941
        }
942

943
        new_fd = fd_reopen(fd, flags);
5,610✔
944
        if (new_fd < 0)
5,610✔
945
                return new_fd;
946

947
        *ret_new_fd = new_fd;
5,610✔
948
        return new_fd;
5,610✔
949
}
950

951
int fd_is_opath(int fd) {
474,790✔
952
        int r;
474,790✔
953

954
        assert(fd >= 0);
474,790✔
955

956
        r = fcntl(fd, F_GETFL);
474,790✔
957
        if (r < 0)
474,790✔
958
                return -errno;
×
959

960
        return FLAGS_SET(r, O_PATH);
474,790✔
961
}
962

963
int fd_vet_accmode(int fd, int mode) {
10,829✔
964
        int flags;
10,829✔
965

966
        /* Check if fd is opened with desired access mode.
967
         *
968
         * Returns > 0 on strict match, == 0 if opened for both reading and writing (partial match),
969
         * -EPROTOTYPE otherwise. O_PATH fds are always refused with -EBADFD.
970
         *
971
         * Note that while on O_DIRECTORY -EISDIR will be returned, this should not be relied upon as
972
         * the flag might not have been specified when open() was called originally. */
973

974
        assert(fd >= 0);
10,829✔
975
        assert(IN_SET(mode, O_RDONLY, O_WRONLY, O_RDWR));
10,829✔
976

977
        flags = fcntl(fd, F_GETFL);
10,829✔
978
        if (flags < 0)
10,829✔
979
                return -errno;
1✔
980

981
        /* O_TMPFILE in userspace is defined with O_DIRECTORY OR'ed in, so explicitly permit it.
982
         *
983
         * C.f. https://elixir.bootlin.com/linux/v6.17.7/source/include/uapi/asm-generic/fcntl.h#L92 */
984
        if (FLAGS_SET(flags, O_DIRECTORY) && !FLAGS_SET(flags, O_TMPFILE))
10,828✔
985
                return -EISDIR;
986

987
        if (FLAGS_SET(flags, O_PATH))
10,828✔
988
                return -EBADFD;
989

990
        flags &= O_ACCMODE_STRICT;
10,824✔
991

992
        if (flags == mode)
10,824✔
993
                return 1;
994

995
        if (flags == O_RDWR)
10,100✔
996
                return 0;
10,095✔
997

998
        return -EPROTOTYPE;
999
}
1000

1001
int fd_is_writable(int fd) {
9,539✔
1002
        int r;
9,539✔
1003

1004
        assert(fd >= 0);
9,539✔
1005

1006
        r = fd_vet_accmode(fd, O_WRONLY);
9,539✔
1007
        if (r >= 0)
9,539✔
1008
                return true;
1009

1010
        if (IN_SET(r, -EPROTOTYPE, -EBADFD, -EISDIR))
3✔
1011
                return false;
2✔
1012

1013
        return r;
1014
}
1015

1016
int fd_verify_safe_flags_full(int fd, int extra_flags) {
619✔
1017
        int flags, unexpected_flags;
619✔
1018

1019
        /* Check if an extrinsic fd is safe to work on (by a privileged service). This ensures that clients
1020
         * can't trick a privileged service into giving access to a file the client doesn't already have
1021
         * access to (especially via something like O_PATH).
1022
         *
1023
         * O_NOFOLLOW: For some reason the kernel will return this flag from fcntl(); it doesn't go away
1024
         *             immediately after open(). It should have no effect whatsoever to an already-opened FD,
1025
         *             and since we refuse O_PATH it should be safe.
1026
         *
1027
         * RAW_O_LARGEFILE: glibc secretly sets this and neglects to hide it from us if we call fcntl.
1028
         *                  See comment in src/basic/include/fcntl.h for more details about this.
1029
         *
1030
         * If 'extra_flags' is specified as non-zero the included flags are also allowed.
1031
         */
1032

1033
        assert(fd >= 0);
619✔
1034

1035
        flags = fcntl(fd, F_GETFL);
619✔
1036
        if (flags < 0)
619✔
1037
                return -errno;
×
1038

1039
        unexpected_flags = flags & ~(O_ACCMODE_STRICT|O_NOFOLLOW|RAW_O_LARGEFILE|extra_flags);
619✔
1040
        if (unexpected_flags != 0)
619✔
1041
                return log_debug_errno(SYNTHETIC_ERRNO(EREMOTEIO),
×
1042
                                       "Unexpected flags set for extrinsic fd: 0%o",
1043
                                       (unsigned) unexpected_flags);
1044

1045
        return flags & (O_ACCMODE_STRICT | extra_flags); /* return the flags variable, but remove the noise */
619✔
1046
}
1047

1048
unsigned read_nr_open(void) {
25,896✔
1049
        _cleanup_free_ char *nr_open = NULL;
25,896✔
1050
        int r;
25,896✔
1051

1052
        /* Returns the kernel's current fd limit, either by reading it of /proc/sys if that works, or using the
1053
         * hard-coded default compiled-in value of current kernels (1M) if not. This call will never fail. */
1054

1055
        r = read_one_line_file("/proc/sys/fs/nr_open", &nr_open);
25,896✔
1056
        if (r < 0)
25,896✔
1057
                log_debug_errno(r, "Failed to read /proc/sys/fs/nr_open, ignoring: %m");
25,896✔
1058
        else {
1059
                unsigned v;
25,896✔
1060

1061
                r = safe_atou(nr_open, &v);
25,896✔
1062
                if (r < 0)
25,896✔
1063
                        log_debug_errno(r, "Failed to parse /proc/sys/fs/nr_open value '%s', ignoring: %m", nr_open);
×
1064
                else
1065
                        return v;
25,896✔
1066
        }
1067

1068
        /* If we fail, fall back to the hard-coded kernel limit of 1024 * 1024. */
1069
        return NR_OPEN_DEFAULT;
1070
}
1071

1072
int fd_get_diskseq(int fd, uint64_t *ret) {
59,954✔
1073
        uint64_t diskseq;
59,954✔
1074

1075
        assert(fd >= 0);
59,954✔
1076
        assert(ret);
59,954✔
1077

1078
        if (ioctl(fd, BLKGETDISKSEQ, &diskseq) < 0) {
59,954✔
1079
                /* Note that the kernel is weird: non-existing ioctls currently return EINVAL
1080
                 * rather than ENOTTY on loopback block devices. They should fix that in the kernel,
1081
                 * but in the meantime we accept both here. */
1082
                if (!ERRNO_IS_NOT_SUPPORTED(errno) && errno != EINVAL)
×
1083
                        return -errno;
×
1084

1085
                return -EOPNOTSUPP;
1086
        }
1087

1088
        *ret = diskseq;
59,954✔
1089

1090
        return 0;
59,954✔
1091
}
1092

1093
int path_is_root_at(int dir_fd, const char *path) {
4,155,367✔
1094
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
4,155,367✔
1095

1096
        _cleanup_close_ int fd = -EBADF;
4,155,367✔
1097
        if (!isempty(path)) {
4,155,367✔
1098
                fd = openat(dir_fd, path, O_PATH|O_DIRECTORY|O_CLOEXEC);
100,553✔
1099
                if (fd < 0)
100,553✔
1100
                        return errno == ENOTDIR ? false : -errno;
16,395✔
1101

1102
                dir_fd = fd;
1103
        }
1104

1105
        _cleanup_close_ int root_fd = openat(AT_FDCWD, "/", O_PATH|O_DIRECTORY|O_CLOEXEC);
8,294,339✔
1106
        if (root_fd < 0)
4,138,972✔
1107
                return -errno;
×
1108

1109
        /* Even if the root directory has the same inode as our fd, the fd may not point to the root
1110
         * directory "/", and we also need to check that the mount ids are the same. Otherwise, a construct
1111
         * like the following could be used to trick us:
1112
         *
1113
         * $ mkdir /tmp/x
1114
         * $ mount --bind / /tmp/x
1115
         */
1116

1117
        return fds_are_same_mount(dir_fd, root_fd);
4,138,972✔
1118
}
1119

1120
int fds_are_same_mount(int fd1, int fd2) {
4,138,986✔
1121
        struct statx sx1 = {}, sx2 = {}; /* explicitly initialize the struct to make msan silent. */
4,138,986✔
1122
        int r;
4,138,986✔
1123

1124
        assert(fd1 >= 0);
4,138,986✔
1125
        assert(fd2 >= 0);
4,138,986✔
1126

1127
        if (statx(fd1, "", AT_EMPTY_PATH, STATX_TYPE|STATX_INO|STATX_MNT_ID, &sx1) < 0)
4,138,986✔
1128
                return -errno;
×
1129

1130
        if (statx(fd2, "", AT_EMPTY_PATH, STATX_TYPE|STATX_INO|STATX_MNT_ID, &sx2) < 0)
4,138,986✔
1131
                return -errno;
×
1132

1133
        /* First, compare inode. If these are different, the fd does not point to the root directory "/". */
1134
        if (!statx_inode_same(&sx1, &sx2))
4,138,986✔
1135
                return false;
1136

1137
        /* Note, statx() does not provide the mount ID and path_get_mnt_id_at() does not work when an old
1138
         * kernel is used. In that case, let's assume that we do not have such spurious mount points in an
1139
         * early boot stage, and silently skip the following check. */
1140

1141
        if (!FLAGS_SET(sx1.stx_mask, STATX_MNT_ID)) {
3,985,734✔
1142
                int mntid;
×
1143

1144
                r = path_get_mnt_id_at_fallback(fd1, "", &mntid);
×
1145
                if (r < 0)
×
1146
                        return r;
×
1147
                assert(mntid >= 0);
×
1148

1149
                sx1.stx_mnt_id = mntid;
×
1150
                sx1.stx_mask |= STATX_MNT_ID;
×
1151
        }
1152

1153
        if (!FLAGS_SET(sx2.stx_mask, STATX_MNT_ID)) {
3,985,734✔
1154
                int mntid;
×
1155

1156
                r = path_get_mnt_id_at_fallback(fd2, "", &mntid);
×
1157
                if (r < 0)
×
1158
                        return r;
×
1159
                assert(mntid >= 0);
×
1160

1161
                sx2.stx_mnt_id = mntid;
×
1162
                sx2.stx_mask |= STATX_MNT_ID;
×
1163
        }
1164

1165
        return statx_mount_same(&sx1, &sx2);
3,985,734✔
1166
}
1167

1168
char* format_proc_fd_path(char buf[static PROC_FD_PATH_MAX], int fd) {
5,129,537✔
1169
        assert(buf);
5,129,537✔
1170
        assert(fd >= 0);
5,129,537✔
1171
        assert_se(snprintf_ok(buf, PROC_FD_PATH_MAX, "/proc/self/fd/%i", fd));
5,129,537✔
1172
        return buf;
5,129,537✔
1173
}
1174

1175
const char* accmode_to_string(int flags) {
178✔
1176
        switch (flags & O_ACCMODE_STRICT) {
178✔
1177
        case O_RDONLY:
1178
                return "ro";
1179
        case O_WRONLY:
3✔
1180
                return "wo";
3✔
1181
        case O_RDWR:
172✔
1182
                return "rw";
172✔
1183
        default:
×
1184
                return NULL;
×
1185
        }
1186
}
1187

1188
char* format_proc_pid_fd_path(char buf[static PROC_PID_FD_PATH_MAX], pid_t pid, int fd) {
1✔
1189
        assert(buf);
1✔
1190
        assert(fd >= 0);
1✔
1191
        assert(pid >= 0);
1✔
1192
        assert_se(snprintf_ok(buf, PROC_PID_FD_PATH_MAX, "/proc/" PID_FMT "/fd/%i", pid == 0 ? getpid_cached() : pid, fd));
1✔
1193
        return buf;
1✔
1194
}
1195

1196
int proc_fd_enoent_errno(void) {
5✔
1197
        int r;
5✔
1198

1199
        /* When ENOENT is returned during the use of FORMAT_PROC_FD_PATH, it can mean two things:
1200
         * that the fd does not exist or that /proc/ is not mounted.
1201
         * Let's make things debuggable and figure out the most appropriate errno. */
1202

1203
        r = proc_mounted();
5✔
1204
        if (r == 0)
5✔
1205
                return -ENOSYS;  /* /proc/ is not available or not set up properly, we're most likely
1206
                                    in some chroot environment. */
1207
        if (r > 0)
5✔
1208
                return -EBADF;   /* If /proc/ is definitely around then this means the fd is not valid. */
5✔
1209

1210
        return -ENOENT;          /* Otherwise let's propagate the original ENOENT. */
1211
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc