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

systemd / systemd / 12919407857

23 Jan 2025 12:04AM UTC coverage: 71.444% (+71.3%) from 0.117%
12919407857

push

github

web-flow
core/device: do not drop backslashes in SYSTEMD_WANTS=/SYSTEMD_USER_WANTS= (#35869)

Let consider the following udev rules:
```
PROGRAM="/usr/bin/systemd-escape foo-bar-baz", ENV{SYSTEMD_WANTS}+="test1@$result.service"
PROGRAM="/usr/bin/systemd-escape aaa-bbb-ccc", ENV{SYSTEMD_WANTS}+="test2@$result.service"
```
Then, a device expectedly gains a property:
```
SYSTEMD_WANTS=test1@foo\x2dbar\x2dbaz.service test2@aaa\x2dbbb\x2dccc.service
```
After the event being processed by udevd, PID1 processes the device, the
property previously was parsed with
`extract_first_word(EXTRACT_UNQUOTE)`, then the device unit gained the
following dependencies:
```
Wants=test1@foox2dbarx2dbaz.service test2@aaax2dbbbx2dccc.service
```
So both `%i` and `%I` for the template services did not match with the
original data, and it was hard to use `systemd-escape` in `PROGRAM=`
udev rule token.

This makes the property parsed with
`extract_first_word(EXTRACT_UNQUOTE|EXTRACT_RETAIN_ESCAPE)`, hence the
device unit now gains the following dependencies:
```
Wants=test1@foo\x2dbar\x2dbaz.service test2@aaa\x2dbbb\x2dccc.service
```
and `%I` for the template services match with the original data.

Fixes a bug caused by ceed8f0c8 (v233).

Fixes #16735.
Replaces #16737 and #35768.

40 of 40 new or added lines in 2 files covered. (100.0%)

407 existing lines in 13 files now uncovered.

291321 of 407761 relevant lines covered (71.44%)

696525.16 hits per line

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

78.57
/src/basic/fd-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <errno.h>
4
#include <fcntl.h>
5
#if WANT_LINUX_FS_H
6
#include <linux/fs.h>
7
#endif
8
#include <linux/magic.h>
9
#include <sys/ioctl.h>
10
#include <sys/resource.h>
11
#include <sys/stat.h>
12
#include <unistd.h>
13

14
#include "alloc-util.h"
15
#include "dirent-util.h"
16
#include "fd-util.h"
17
#include "fileio.h"
18
#include "fs-util.h"
19
#include "io-util.h"
20
#include "macro.h"
21
#include "missing_fcntl.h"
22
#include "missing_fs.h"
23
#include "missing_syscall.h"
24
#include "mountpoint-util.h"
25
#include "parse-util.h"
26
#include "path-util.h"
27
#include "process-util.h"
28
#include "socket-util.h"
29
#include "sort-util.h"
30
#include "stat-util.h"
31
#include "stdio-util.h"
32
#include "tmpfile-util.h"
33

34
/* The maximum number of iterations in the loop to close descriptors in the fallback case
35
 * when /proc/self/fd/ is inaccessible. */
36
#define MAX_FD_LOOP_LIMIT (1024*1024)
37

38
int close_nointr(int fd) {
29,402,150✔
39
        assert(fd >= 0);
29,402,150✔
40

41
        if (close(fd) >= 0)
29,402,150✔
42
                return 0;
43

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

56
        return -errno;
15,418✔
57
}
58

59
int safe_close(int fd) {
76,189,035✔
60
        /*
61
         * Like close_nointr() but cannot fail. Guarantees errno is unchanged. Is a noop for negative fds,
62
         * and returns -EBADF, so that it can be used in this syntax:
63
         *
64
         * fd = safe_close(fd);
65
         */
66

67
        if (fd >= 0) {
76,189,035✔
68
                PROTECT_ERRNO;
×
69

70
                /* The kernel might return pretty much any error code
71
                 * via close(), but the fd will be closed anyway. The
72
                 * only condition we want to check for here is whether
73
                 * the fd was invalid at all... */
74

75
                assert_se(close_nointr(fd) != -EBADF);
28,981,691✔
76
        }
77

78
        return -EBADF;
76,189,035✔
79
}
80

81
void safe_close_pair(int p[static 2]) {
467,807✔
82
        assert(p);
467,807✔
83

84
        if (p[0] == p[1]) {
467,807✔
85
                /* Special case pairs which use the same fd in both
86
                 * directions... */
87
                p[0] = p[1] = safe_close(p[0]);
436,425✔
88
                return;
436,425✔
89
        }
90

91
        p[0] = safe_close(p[0]);
31,382✔
92
        p[1] = safe_close(p[1]);
31,382✔
93
}
94

95
void close_many(const int fds[], size_t n_fds) {
2,761,660✔
96
        assert(fds || n_fds == 0);
2,761,660✔
97

98
        FOREACH_ARRAY(fd, fds, n_fds)
2,809,903✔
99
                safe_close(*fd);
48,243✔
100
}
2,761,660✔
101

102
void close_many_unset(int fds[], size_t n_fds) {
56✔
103
        assert(fds || n_fds == 0);
56✔
104

105
        FOREACH_ARRAY(fd, fds, n_fds)
57✔
106
                *fd = safe_close(*fd);
1✔
107
}
56✔
108

109
void close_many_and_free(int *fds, size_t n_fds) {
115✔
110
        assert(fds || n_fds == 0);
115✔
111

112
        close_many(fds, n_fds);
115✔
113
        free(fds);
115✔
114
}
115✔
115

116
int fclose_nointr(FILE *f) {
1,729,474✔
117
        assert(f);
1,729,474✔
118

119
        /* Same as close_nointr(), but for fclose() */
120

121
        errno = 0; /* Extra safety: if the FILE* object is not encapsulating an fd, it might not set errno
1,729,474✔
122
                    * correctly. Let's hence initialize it to zero first, so that we aren't confused by any
123
                    * prior errno here */
124
        if (fclose(f) == 0)
1,729,474✔
125
                return 0;
126

127
        if (errno == EINTR)
×
128
                return 0;
129

130
        return errno_or_else(EIO);
×
131
}
132

133
FILE* safe_fclose(FILE *f) {
3,447,762✔
134

135
        /* Same as safe_close(), but for fclose() */
136

137
        if (f) {
3,447,762✔
138
                PROTECT_ERRNO;
×
139

140
                assert_se(fclose_nointr(f) != -EBADF);
1,729,474✔
141
        }
142

143
        return NULL;
3,447,762✔
144
}
145

146
DIR* safe_closedir(DIR *d) {
×
147

148
        if (d) {
×
149
                PROTECT_ERRNO;
×
150

151
                assert_se(closedir(d) >= 0 || errno != EBADF);
×
152
        }
153

154
        return NULL;
×
155
}
156

157
int fd_nonblock(int fd, bool nonblock) {
1,831,186✔
158
        int flags, nflags;
1,831,186✔
159

160
        assert(fd >= 0);
1,831,186✔
161

162
        flags = fcntl(fd, F_GETFL, 0);
1,831,186✔
163
        if (flags < 0)
1,831,186✔
164
                return -errno;
×
165

166
        nflags = UPDATE_FLAG(flags, O_NONBLOCK, nonblock);
1,831,186✔
167
        if (nflags == flags)
1,831,186✔
168
                return 0;
169

170
        if (fcntl(fd, F_SETFL, nflags) < 0)
1,810,700✔
171
                return -errno;
×
172

173
        return 1;
174
}
175

176
int stdio_disable_nonblock(void) {
13,696✔
177
        int ret = 0;
13,696✔
178

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

182
        RET_GATHER(ret, fd_nonblock(STDIN_FILENO, false));
13,696✔
183
        RET_GATHER(ret, fd_nonblock(STDOUT_FILENO, false));
13,696✔
184
        RET_GATHER(ret, fd_nonblock(STDERR_FILENO, false));
13,696✔
185

186
        return ret;
13,696✔
187
}
188

189
int fd_cloexec(int fd, bool cloexec) {
95,001✔
190
        int flags, nflags;
95,001✔
191

192
        assert(fd >= 0);
95,001✔
193

194
        flags = fcntl(fd, F_GETFD, 0);
95,001✔
195
        if (flags < 0)
95,001✔
196
                return -errno;
×
197

198
        nflags = UPDATE_FLAG(flags, FD_CLOEXEC, cloexec);
95,001✔
199
        if (nflags == flags)
95,001✔
200
                return 0;
201

202
        return RET_NERRNO(fcntl(fd, F_SETFD, nflags));
86,867✔
203
}
204

205
int fd_cloexec_many(const int fds[], size_t n_fds, bool cloexec) {
62✔
206
        int r = 0;
62✔
207

208
        assert(fds || n_fds == 0);
62✔
209

210
        FOREACH_ARRAY(fd, fds, n_fds) {
82✔
211
                if (*fd < 0) /* Skip gracefully over already invalidated fds */
20✔
212
                        continue;
×
213

214
                RET_GATHER(r, fd_cloexec(*fd, cloexec));
20✔
215
        }
216

217
        return r;
62✔
218
}
219

220
static bool fd_in_set(int fd, const int fds[], size_t n_fds) {
34,124✔
221
        assert(fd >= 0);
34,124✔
222
        assert(fds || n_fds == 0);
34,124✔
223

224
        FOREACH_ARRAY(i, fds, n_fds) {
21,058,643✔
225
                if (*i < 0)
21,028,226✔
226
                        continue;
×
227

228
                if (*i == fd)
21,028,226✔
229
                        return true;
230
        }
231

232
        return false;
233
}
234

235
int get_max_fd(void) {
9✔
236
        struct rlimit rl;
9✔
237
        rlim_t m;
9✔
238

239
        /* Return the highest possible fd, based RLIMIT_NOFILE, but enforcing FD_SETSIZE-1 as lower boundary
240
         * and INT_MAX as upper boundary. */
241

242
        if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
9✔
243
                return -errno;
×
244

245
        m = MAX(rl.rlim_cur, rl.rlim_max);
9✔
246
        if (m < FD_SETSIZE) /* Let's always cover at least 1024 fds */
9✔
247
                return FD_SETSIZE-1;
248

249
        if (m == RLIM_INFINITY || m > INT_MAX) /* Saturate on overflow. After all fds are "int", hence can
9✔
250
                                                * never be above INT_MAX */
251
                return INT_MAX;
252

253
        return (int) (m - 1);
9✔
254
}
255

256
static int close_all_fds_frugal(const int except[], size_t n_except) {
4✔
257
        int max_fd, r = 0;
4✔
258

259
        assert(except || n_except == 0);
4✔
260

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

266
        max_fd = get_max_fd();
4✔
267
        if (max_fd < 0)
4✔
268
                return max_fd;
4✔
269

270
        /* Refuse to do the loop over more too many elements. It's better to fail immediately than to
271
         * spin the CPU for a long time. */
272
        if (max_fd > MAX_FD_LOOP_LIMIT)
4✔
273
                return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
×
274
                                       "Refusing to loop over %d potential fds.", max_fd);
275

276
        for (int fd = 3; fd >= 0; fd = fd < max_fd ? fd + 1 : -EBADF) {
55,980✔
277
                int q;
27,988✔
278

279
                if (fd_in_set(fd, except, n_except))
27,988✔
280
                        continue;
2,571✔
281

282
                q = close_nointr(fd);
25,417✔
283
                if (q != -EBADF)
25,417✔
284
                        RET_GATHER(r, q);
10,000✔
285
        }
286

287
        return r;
288
}
289

290
static bool have_close_range = true; /* Assume we live in the future */
291

292
static int close_all_fds_special_case(const int except[], size_t n_except) {
44,563✔
293
        assert(n_except == 0 || except);
44,563✔
294

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

299
        if (!have_close_range)
44,563✔
300
                return 0;
301

302
        if (n_except == 1 && except[0] < 0) /* Minor optimization: if we only got one fd, and it's invalid,
44,559✔
303
                                             * we got none */
304
                n_except = 0;
305

306
        switch (n_except) {
44,559✔
307

308
        case 0:
17,098✔
309
                /* Close everything. Yay! */
310

311
                if (close_range(3, INT_MAX, 0) >= 0)
17,098✔
312
                        return 1;
313

314
                if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) {
×
315
                        have_close_range = false;
×
316
                        return 0;
×
317
                }
318

319
                return -errno;
×
320

321
        case 1:
2,887✔
322
                /* Close all but exactly one, then we don't need no sorting. This is a pretty common
323
                 * case, hence let's handle it specially. */
324

325
                if ((except[0] <= 3 || close_range(3, except[0]-1, 0) >= 0) &&
2,887✔
326
                    (except[0] >= INT_MAX || close_range(MAX(3, except[0]+1), -1, 0) >= 0))
2,887✔
327
                        return 1;
2,887✔
328

329
                if (ERRNO_IS_NOT_SUPPORTED(errno) || ERRNO_IS_PRIVILEGE(errno)) {
×
330
                        have_close_range = false;
×
331
                        return 0;
×
332
                }
333

334
                return -errno;
×
335

336
        default:
337
                return 0;
338
        }
339
}
340

341
int close_all_fds_without_malloc(const int except[], size_t n_except) {
×
342
        int r;
×
343

344
        assert(n_except == 0 || except);
×
345

346
        r = close_all_fds_special_case(except, n_except);
×
347
        if (r < 0)
×
348
                return r;
349
        if (r > 0) /* special case worked! */
×
350
                return 0;
351

352
        return close_all_fds_frugal(except, n_except);
×
353
}
354

355
int close_all_fds(const int except[], size_t n_except) {
44,563✔
356
        _cleanup_closedir_ DIR *d = NULL;
44,563✔
357
        int r = 0;
44,563✔
358

359
        assert(n_except == 0 || except);
44,563✔
360

361
        r = close_all_fds_special_case(except, n_except);
44,563✔
362
        if (r < 0)
44,563✔
363
                return r;
364
        if (r > 0) /* special case worked! */
44,563✔
365
                return 0;
366

367
        if (have_close_range) {
24,578✔
368
                _cleanup_free_ int *sorted_malloc = NULL;
24,574✔
369
                size_t n_sorted;
24,574✔
370
                int *sorted;
24,574✔
371

372
                /* In the best case we have close_range() to close all fds between a start and an end fd,
373
                 * which we can use on the "inverted" exception array, i.e. all intervals between all
374
                 * adjacent pairs from the sorted exception array. This changes loop complexity from O(n)
375
                 * where n is number of open fds to O(mâ‹…log(m)) where m is the number of fds to keep
376
                 * open. Given that we assume n ≫ m that's preferable to us. */
377

378
                assert(n_except < SIZE_MAX);
24,574✔
379
                n_sorted = n_except + 1;
24,574✔
380

381
                if (n_sorted > 64) /* Use heap for large numbers of fds, stack otherwise */
24,574✔
382
                        sorted = sorted_malloc = new(int, n_sorted);
4✔
383
                else
384
                        sorted = newa(int, n_sorted);
24,570✔
385

386
                if (sorted) {
24,574✔
387
                        memcpy(sorted, except, n_except * sizeof(int));
24,574✔
388

389
                        /* Let's add fd 2 to the list of fds, to simplify the loop below, as this
390
                         * allows us to cover the head of the array the same way as the body */
391
                        sorted[n_sorted-1] = 2;
24,574✔
392

393
                        typesafe_qsort(sorted, n_sorted, cmp_int);
24,574✔
394

395
                        for (size_t i = 0; i < n_sorted-1; i++) {
111,151✔
396
                                int start, end;
86,579✔
397

398
                                start = MAX(sorted[i], 2); /* The first three fds shall always remain open */
86,579✔
399
                                end = MAX(sorted[i+1], 2);
86,579✔
400

401
                                assert(end >= start);
86,579✔
402

403
                                if (end - start <= 1)
86,579✔
404
                                        continue;
33,707✔
405

406
                                /* Close everything between the start and end fds (both of which shall stay open) */
407
                                if (close_range(start + 1, end - 1, 0) < 0) {
52,872✔
408
                                        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
2✔
409
                                                return -errno;
×
410

411
                                        have_close_range = false;
2✔
412
                                        break;
2✔
413
                                }
414
                        }
415

416
                        if (have_close_range) {
24,574✔
417
                                /* The loop succeeded. Let's now close everything beyond the end */
418

419
                                if (sorted[n_sorted-1] >= INT_MAX) /* Dont let the addition below overflow */
24,572✔
420
                                        return 0;
421

422
                                if (close_range(sorted[n_sorted-1] + 1, INT_MAX, 0) >= 0)
24,572✔
423
                                        return 0;
424

425
                                if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
×
426
                                        return -errno;
×
427

428
                                have_close_range = false;
×
429
                        }
430
                }
431

432
                /* Fallback on OOM or if close_range() is not supported */
433
        }
434

435
        d = opendir("/proc/self/fd");
6✔
436
        if (!d)
6✔
437
                return close_all_fds_frugal(except, n_except); /* ultimate fallback if /proc/ is not available */
4✔
438

439
        FOREACH_DIRENT(de, d, return -errno) {
6,150✔
440
                int fd = -EBADF, q;
6,144✔
441

442
                if (!IN_SET(de->d_type, DT_LNK, DT_UNKNOWN))
6,144✔
443
                        continue;
×
444

445
                fd = parse_fd(de->d_name);
6,144✔
446
                if (fd < 0)
6,144✔
447
                        /* Let's better ignore this, just in case */
448
                        continue;
×
449

450
                if (fd < 3)
6,144✔
451
                        continue;
6✔
452

453
                if (fd == dirfd(d))
6,138✔
454
                        continue;
2✔
455

456
                if (fd_in_set(fd, except, n_except))
6,136✔
457
                        continue;
1,136✔
458

459
                q = close_nointr(fd);
5,000✔
460
                if (q < 0 && q != -EBADF && r >= 0) /* Valgrind has its own FD and doesn't want to have it closed */
5,000✔
461
                        r = q;
×
462
        }
463

464
        return r;
465
}
466

467
int pack_fds(int fds[], size_t n_fds) {
11,108✔
468
        if (n_fds <= 0)
11,108✔
469
                return 0;
470

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

478
        assert(fds);
1,559✔
479

480
        for (int start = 0;;) {
481
                int restart_from = -1;
1,559✔
482

483
                for (int i = start; i < (int) n_fds; i++) {
4,120✔
484
                        int nfd;
2,561✔
485

486
                        /* Already at right index? */
487
                        if (fds[i] == i + 3)
2,561✔
488
                                continue;
×
489

490
                        nfd = fcntl(fds[i], F_DUPFD, i + 3);
2,561✔
491
                        if (nfd < 0)
2,561✔
492
                                return -errno;
×
493

494
                        safe_close(fds[i]);
2,561✔
495
                        fds[i] = nfd;
2,561✔
496

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

503
                if (restart_from < 0)
1,559✔
504
                        break;
505

506
                start = restart_from;
507
        }
508

509
        assert(fds[0] == 3);
1,559✔
510

511
        return 0;
512
}
513

514
int fd_validate(int fd) {
117,518✔
515
        if (fd < 0)
117,518✔
516
                return -EBADF;
517

518
        if (fcntl(fd, F_GETFD) < 0)
117,516✔
519
                return -errno;
43,517✔
520

521
        return 0;
522
}
523

524
int same_fd(int a, int b) {
24,805✔
525
        struct stat sta, stb;
24,805✔
526
        pid_t pid;
24,805✔
527
        int r, fa, fb;
24,805✔
528

529
        assert(a >= 0);
24,805✔
530
        assert(b >= 0);
24,805✔
531

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

541
        if (a == b) {
24,805✔
542
                /* Let's validate that the fd is valid */
543
                r = fd_validate(a);
7✔
544
                if (r < 0)
7✔
545
                        return r;
24,805✔
546

547
                return true;
6✔
548
        }
549

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

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

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

575
        /* Try to use kcmp() if we have it. */
576
        pid = getpid_cached();
7,306✔
577
        r = kcmp(pid, pid, KCMP_FILE, a, b);
7,306✔
578
        if (r >= 0)
7,306✔
579
                return !r;
7,305✔
580
        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
1✔
581
                return -errno;
1✔
582

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

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

590
        if (!stat_inode_same(&sta, &stb))
×
591
                return false;
592

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

596
        if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
×
597
                return false;
598

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

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

609
        return fa == fb;
×
610
}
611

612
void cmsg_close_all(struct msghdr *mh) {
141,946✔
613
        assert(mh);
141,946✔
614

615
        struct cmsghdr *cmsg;
141,946✔
616
        CMSG_FOREACH(cmsg, mh) {
530,360✔
617
                if (cmsg->cmsg_level != SOL_SOCKET)
123,234✔
618
                        continue;
×
619

620
                if (cmsg->cmsg_type == SCM_RIGHTS)
123,234✔
621
                        close_many(CMSG_TYPED_DATA(cmsg, int),
×
622
                                   (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
×
623
                else if (cmsg->cmsg_type == SCM_PIDFD) {
123,234✔
624
                        assert(cmsg->cmsg_len == CMSG_LEN(sizeof(int)));
×
625
                        safe_close(*CMSG_TYPED_DATA(cmsg, int));
×
626
                }
627
        }
628
}
141,946✔
629

630
bool fdname_is_valid(const char *s) {
15,993✔
631
        const char *p;
15,993✔
632

633
        /* Validates a name for $LISTEN_FDNAMES. We basically allow
634
         * everything ASCII that's not a control character. Also, as
635
         * special exception the ":" character is not allowed, as we
636
         * use that as field separator in $LISTEN_FDNAMES.
637
         *
638
         * Note that the empty string is explicitly allowed
639
         * here. However, we limit the length of the names to 255
640
         * characters. */
641

642
        if (!s)
15,993✔
643
                return false;
644

645
        for (p = s; *p; p++) {
259,162✔
646
                if (*p < ' ')
243,174✔
647
                        return false;
648
                if (*p >= 127)
243,174✔
649
                        return false;
650
                if (*p == ':')
243,174✔
651
                        return false;
652
        }
653

654
        return p - s <= FDNAME_MAX;
15,988✔
655
}
656

657
int fd_get_path(int fd, char **ret) {
1,797,667✔
658
        int r;
1,797,667✔
659

660
        assert(fd >= 0 || fd == AT_FDCWD);
1,797,667✔
661

662
        if (fd == AT_FDCWD)
1,797,667✔
663
                return safe_getcwd(ret);
5,106✔
664

665
        r = readlink_malloc(FORMAT_PROC_FD_PATH(fd), ret);
1,792,561✔
666
        if (r == -ENOENT)
1,792,561✔
667
                return proc_fd_enoent_errno();
4✔
668
        return r;
669
}
670

671
int move_fd(int from, int to, int cloexec) {
25,687✔
672
        int r;
25,687✔
673

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

678
        if (from < 0)
25,687✔
679
                return -EBADF;
680
        if (to < 0)
25,687✔
681
                return -EBADF;
682

683
        if (from == to) {
25,687✔
684

685
                if (cloexec >= 0) {
×
686
                        r = fd_cloexec(to, cloexec);
×
687
                        if (r < 0)
×
688
                                return r;
689
                }
690

691
                return to;
×
692
        }
693

694
        if (cloexec < 0) {
25,687✔
695
                int fl;
×
696

697
                fl = fcntl(from, F_GETFD, 0);
×
698
                if (fl < 0)
×
699
                        return -errno;
×
700

701
                cloexec = FLAGS_SET(fl, FD_CLOEXEC);
×
702
        }
703

704
        r = dup3(from, to, cloexec ? O_CLOEXEC : 0);
51,374✔
705
        if (r < 0)
25,687✔
706
                return -errno;
×
707

708
        assert(r == to);
25,687✔
709

710
        safe_close(from);
25,687✔
711

712
        return to;
25,687✔
713
}
714

715
int fd_move_above_stdio(int fd) {
631,786✔
716
        int flags, copy;
631,786✔
717
        PROTECT_ERRNO;
631,786✔
718

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

732
        if (fd < 0 || fd > 2)
631,786✔
733
                return fd;
734

735
        flags = fcntl(fd, F_GETFD, 0);
102✔
736
        if (flags < 0)
102✔
737
                return fd;
738

739
        if (flags & FD_CLOEXEC)
102✔
740
                copy = fcntl(fd, F_DUPFD_CLOEXEC, 3);
100✔
741
        else
742
                copy = fcntl(fd, F_DUPFD, 3);
2✔
743
        if (copy < 0)
102✔
744
                return fd;
745

746
        assert(copy > 2);
102✔
747

748
        (void) close(fd);
102✔
749
        return copy;
750
}
751

752
int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd) {
14,065✔
753
        int fd[3] = { original_input_fd,             /* Put together an array of fds we work on */
14,065✔
754
                      original_output_fd,
755
                      original_error_fd },
756
            null_fd = -EBADF,                        /* If we open /dev/null, we store the fd to it here */
14,065✔
757
            copy_fd[3] = EBADF_TRIPLET,              /* This contains all fds we duplicate here
14,065✔
758
                                                      * temporarily, and hence need to close at the end. */
759
            r;
760
        bool null_readable, null_writable;
14,065✔
761

762
        /* Sets up stdin, stdout, stderr with the three file descriptors passed in. If any of the descriptors
763
         * is specified as -EBADF it will be connected with /dev/null instead. If any of the file descriptors
764
         * is passed as itself (e.g. stdin as STDIN_FILENO) it is left unmodified, but the O_CLOEXEC bit is
765
         * turned off should it be on.
766
         *
767
         * Note that if any of the passed file descriptors are > 2 they will be closed — both on success and
768
         * on failure! Thus, callers should assume that when this function returns the input fds are
769
         * invalidated.
770
         *
771
         * Note that when this function fails stdin/stdout/stderr might remain half set up!
772
         *
773
         * O_CLOEXEC is turned off for all three file descriptors (which is how it should be for
774
         * stdin/stdout/stderr). */
775

776
        null_readable = original_input_fd < 0;
14,065✔
777
        null_writable = original_output_fd < 0 || original_error_fd < 0;
14,065✔
778

779
        /* First step, open /dev/null once, if we need it */
780
        if (null_readable || null_writable) {
14,065✔
781

782
                /* Let's open this with O_CLOEXEC first, and convert it to non-O_CLOEXEC when we move the fd to the final position. */
783
                null_fd = open("/dev/null", (null_readable && null_writable ? O_RDWR :
23,418✔
784
                                             null_readable ? O_RDONLY : O_WRONLY) | O_CLOEXEC);
11,641✔
785
                if (null_fd < 0) {
11,777✔
786
                        r = -errno;
×
787
                        goto finish;
×
788
                }
789

790
                /* If this fd is in the 0…2 range, let's move it out of it */
791
                if (null_fd < 3) {
11,777✔
792
                        int copy;
75✔
793

794
                        copy = fcntl(null_fd, F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
75✔
795
                        if (copy < 0) {
75✔
796
                                r = -errno;
×
797
                                goto finish;
×
798
                        }
799

800
                        close_and_replace(null_fd, copy);
75✔
801
                }
802
        }
803

804
        /* Let's assemble fd[] with the fds to install in place of stdin/stdout/stderr */
805
        for (int i = 0; i < 3; i++)
56,260✔
806
                if (fd[i] < 0)
42,195✔
807
                        fd[i] = null_fd;        /* A negative parameter means: connect this one to /dev/null */
12,046✔
808
                else if (fd[i] != i && fd[i] < 3) {
30,149✔
809
                        /* 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. */
810
                        copy_fd[i] = fcntl(fd[i], F_DUPFD_CLOEXEC, 3); /* Duplicate this with O_CLOEXEC set */
73✔
811
                        if (copy_fd[i] < 0) {
73✔
812
                                r = -errno;
×
813
                                goto finish;
×
814
                        }
815

816
                        fd[i] = copy_fd[i];
73✔
817
                }
818

819
        /* At this point we now have the fds to use in fd[], and they are all above the stdio range, so that
820
         * we have freedom to move them around. If the fds already were at the right places then the specific
821
         * fds are -EBADF. Let's now move them to the right places. This is the point of no return. */
822
        for (int i = 0; i < 3; i++)
56,260✔
823
                if (fd[i] == i) {
42,195✔
824
                        /* fd is already in place, but let's make sure O_CLOEXEC is off */
825
                        r = fd_cloexec(i, false);
4,378✔
826
                        if (r < 0)
4,378✔
827
                                goto finish;
×
828
                } else {
829
                        assert(fd[i] > 2);
37,817✔
830

831
                        if (dup2(fd[i], i) < 0) { /* Turns off O_CLOEXEC on the new fd. */
37,817✔
832
                                r = -errno;
×
833
                                goto finish;
×
834
                        }
835
                }
836

837
        r = 0;
838

839
finish:
14,065✔
840
        /* Close the original fds, but only if they were outside of the stdio range. Also, properly check for the same
841
         * fd passed in multiple times. */
842
        safe_close_above_stdio(original_input_fd);
14,065✔
843
        if (original_output_fd != original_input_fd)
14,065✔
844
                safe_close_above_stdio(original_output_fd);
13,765✔
845
        if (original_error_fd != original_input_fd && original_error_fd != original_output_fd)
14,065✔
846
                safe_close_above_stdio(original_error_fd);
13,593✔
847

848
        /* Close the copies we moved > 2 */
849
        close_many(copy_fd, 3);
14,065✔
850

851
        /* Close our null fd, if it's > 2 */
852
        safe_close_above_stdio(null_fd);
14,065✔
853

854
        return r;
14,065✔
855
}
856

857
int fd_reopen(int fd, int flags) {
1,531,369✔
858
        assert(fd >= 0 || fd == AT_FDCWD);
1,531,369✔
859
        assert(!FLAGS_SET(flags, O_CREAT));
1,531,369✔
860

861
        /* Reopens the specified fd with new flags. This is useful for convert an O_PATH fd into a regular one, or to
862
         * turn O_RDWR fds into O_RDONLY fds.
863
         *
864
         * This doesn't work on sockets (since they cannot be open()ed, ever).
865
         *
866
         * This implicitly resets the file read index to 0.
867
         *
868
         * If AT_FDCWD is specified as file descriptor gets an fd to the current cwd.
869
         *
870
         * If the specified file descriptor refers to a symlink via O_PATH, then this function cannot be used
871
         * to follow that symlink. Because we cannot have non-O_PATH fds to symlinks reopening it without
872
         * O_PATH will always result in -ELOOP. Or in other words: if you have an O_PATH fd to a symlink you
873
         * can reopen it only if you pass O_PATH again. */
874

875
        if (FLAGS_SET(flags, O_NOFOLLOW))
1,531,369✔
876
                /* O_NOFOLLOW is not allowed in fd_reopen(), because after all this is primarily implemented
877
                 * via a symlink-based interface in /proc/self/fd. Let's refuse this here early. Note that
878
                 * the kernel would generate ELOOP here too, hence this manual check is mostly redundant –
879
                 * the only reason we add it here is so that the O_DIRECTORY special case (see below) behaves
880
                 * the same way as the non-O_DIRECTORY case. */
881
                return -ELOOP;
1,531,369✔
882

883
        if (FLAGS_SET(flags, O_DIRECTORY) || fd == AT_FDCWD)
1,531,363✔
884
                /* If we shall reopen the fd as directory we can just go via "." and thus bypass the whole
885
                 * magic /proc/ directory, and make ourselves independent of that being mounted. */
886
                return RET_NERRNO(openat(fd, ".", flags | O_DIRECTORY));
224,625✔
887

888
        int new_fd = open(FORMAT_PROC_FD_PATH(fd), flags);
1,306,744✔
889
        if (new_fd < 0) {
1,306,744✔
890
                if (errno != ENOENT)
117✔
891
                        return -errno;
114✔
892

893
                return proc_fd_enoent_errno();
3✔
894
        }
895

896
        return new_fd;
897
}
898

899
int fd_reopen_propagate_append_and_position(int fd, int flags) {
26✔
900
        /* Invokes fd_reopen(fd, flags), but propagates O_APPEND if set on original fd, and also tries to
901
         * keep current file position.
902
         *
903
         * You should use this if the original fd potentially is O_APPEND, otherwise we get rather
904
         * "unexpected" behavior. Unless you intentionally want to overwrite pre-existing data, and have
905
         * your output overwritten by the next user.
906
         *
907
         * Use case: "systemd-run --pty >> some-log".
908
         *
909
         * The "keep position" part is obviously nonsense for the O_APPEND case, but should reduce surprises
910
         * if someone carefully pre-positioned the passed in original input or non-append output FDs. */
911

912
        assert(fd >= 0);
26✔
913
        assert(!(flags & (O_APPEND|O_DIRECTORY)));
26✔
914

915
        int existing_flags = fcntl(fd, F_GETFL);
26✔
916
        if (existing_flags < 0)
26✔
917
                return -errno;
×
918

919
        int new_fd = fd_reopen(fd, flags | (existing_flags & O_APPEND));
26✔
920
        if (new_fd < 0)
26✔
921
                return new_fd;
922

923
        /* Try to adjust the offset, but ignore errors. */
924
        off_t p = lseek(fd, 0, SEEK_CUR);
18✔
925
        if (p > 0) {
18✔
926
                off_t new_p = lseek(new_fd, p, SEEK_SET);
×
927
                if (new_p < 0)
×
928
                        log_debug_errno(errno,
×
929
                                        "Failed to propagate file position for re-opened fd %d, ignoring: %m",
930
                                        fd);
931
                else if (new_p != p)
×
932
                        log_debug("Failed to propagate file position for re-opened fd %d (%lld != %lld), ignoring.",
×
933
                                  fd, (long long) new_p, (long long) p);
934
        }
935

936
        return new_fd;
937
}
938

939
int fd_reopen_condition(
1,177,302✔
940
                int fd,
941
                int flags,
942
                int mask,
943
                int *ret_new_fd) {
944

945
        int r, new_fd;
1,177,302✔
946

947
        assert(fd >= 0);
1,177,302✔
948
        assert(!FLAGS_SET(flags, O_CREAT));
1,177,302✔
949

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

954
        r = fcntl(fd, F_GETFL);
1,177,302✔
955
        if (r < 0)
1,177,302✔
956
                return -errno;
×
957

958
        if ((r & mask) == (flags & mask)) {
1,177,302✔
959
                *ret_new_fd = -EBADF;
1,173,306✔
960
                return fd;
1,173,306✔
961
        }
962

963
        new_fd = fd_reopen(fd, flags);
3,996✔
964
        if (new_fd < 0)
3,996✔
965
                return new_fd;
966

967
        *ret_new_fd = new_fd;
3,996✔
968
        return new_fd;
3,996✔
969
}
970

971
int fd_is_opath(int fd) {
81✔
972
        int r;
81✔
973

974
        assert(fd >= 0);
81✔
975

976
        r = fcntl(fd, F_GETFL);
81✔
977
        if (r < 0)
81✔
978
                return -errno;
×
979

980
        return FLAGS_SET(r, O_PATH);
81✔
981
}
982

983
int fd_verify_safe_flags_full(int fd, int extra_flags) {
444✔
984
        int flags, unexpected_flags;
444✔
985

986
        /* Check if an extrinsic fd is safe to work on (by a privileged service). This ensures that clients
987
         * can't trick a privileged service into giving access to a file the client doesn't already have
988
         * access to (especially via something like O_PATH).
989
         *
990
         * O_NOFOLLOW: For some reason the kernel will return this flag from fcntl(); it doesn't go away
991
         *             immediately after open(). It should have no effect whatsoever to an already-opened FD,
992
         *             and since we refuse O_PATH it should be safe.
993
         *
994
         * RAW_O_LARGEFILE: glibc secretly sets this and neglects to hide it from us if we call fcntl.
995
         *                  See comment in missing_fcntl.h for more details about this.
996
         *
997
         * If 'extra_flags' is specified as non-zero the included flags are also allowed.
998
         */
999

1000
        assert(fd >= 0);
444✔
1001

1002
        flags = fcntl(fd, F_GETFL);
444✔
1003
        if (flags < 0)
444✔
1004
                return -errno;
×
1005

1006
        unexpected_flags = flags & ~(O_ACCMODE|O_NOFOLLOW|RAW_O_LARGEFILE|extra_flags);
444✔
1007
        if (unexpected_flags != 0)
444✔
1008
                return log_debug_errno(SYNTHETIC_ERRNO(EREMOTEIO),
×
1009
                                       "Unexpected flags set for extrinsic fd: 0%o",
1010
                                       (unsigned) unexpected_flags);
1011

1012
        return flags & (O_ACCMODE | extra_flags); /* return the flags variable, but remove the noise */
444✔
1013
}
1014

1015
int read_nr_open(void) {
27,751✔
1016
        _cleanup_free_ char *nr_open = NULL;
27,751✔
1017
        int r;
27,751✔
1018

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

1022
        r = read_one_line_file("/proc/sys/fs/nr_open", &nr_open);
27,751✔
1023
        if (r < 0)
27,751✔
1024
                log_debug_errno(r, "Failed to read /proc/sys/fs/nr_open, ignoring: %m");
27,751✔
1025
        else {
1026
                int v;
27,748✔
1027

1028
                r = safe_atoi(nr_open, &v);
27,748✔
1029
                if (r < 0)
27,748✔
1030
                        log_debug_errno(r, "Failed to parse /proc/sys/fs/nr_open value '%s', ignoring: %m", nr_open);
×
1031
                else
1032
                        return v;
27,748✔
1033
        }
1034

1035
        /* If we fail, fall back to the hard-coded kernel limit of 1024 * 1024. */
1036
        return 1024 * 1024;
1037
}
1038

1039
int fd_get_diskseq(int fd, uint64_t *ret) {
58,847✔
1040
        uint64_t diskseq;
58,847✔
1041

1042
        assert(fd >= 0);
58,847✔
1043
        assert(ret);
58,847✔
1044

1045
        if (ioctl(fd, BLKGETDISKSEQ, &diskseq) < 0) {
58,847✔
1046
                /* Note that the kernel is weird: non-existing ioctls currently return EINVAL
1047
                 * rather than ENOTTY on loopback block devices. They should fix that in the kernel,
1048
                 * but in the meantime we accept both here. */
1049
                if (!ERRNO_IS_NOT_SUPPORTED(errno) && errno != EINVAL)
×
1050
                        return -errno;
×
1051

1052
                return -EOPNOTSUPP;
1053
        }
1054

1055
        *ret = diskseq;
58,847✔
1056

1057
        return 0;
58,847✔
1058
}
1059

1060
int path_is_root_at(int dir_fd, const char *path) {
2,466,192✔
1061
        _cleanup_close_ int fd = -EBADF, pfd = -EBADF;
2,466,192✔
1062

1063
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
2,466,192✔
1064

1065
        if (!isempty(path)) {
2,466,192✔
1066
                fd = openat(dir_fd, path, O_PATH|O_DIRECTORY|O_CLOEXEC);
122,932✔
1067
                if (fd < 0)
122,932✔
1068
                        return errno == ENOTDIR ? false : -errno;
13,958✔
1069

1070
                dir_fd = fd;
1071
        }
1072

1073
        pfd = openat(dir_fd, "..", O_PATH|O_DIRECTORY|O_CLOEXEC);
2,452,234✔
1074
        if (pfd < 0)
2,452,234✔
1075
                return errno == ENOTDIR ? false : -errno;
2✔
1076

1077
        /* Even if the parent directory has the same inode, the fd may not point to the root directory "/",
1078
         * and we also need to check that the mount ids are the same. Otherwise, a construct like the
1079
         * following could be used to trick us:
1080
         *
1081
         * $ mkdir /tmp/x /tmp/x/y
1082
         * $ mount --bind /tmp/x /tmp/x/y
1083
         */
1084

1085
        return fds_are_same_mount(dir_fd, pfd);
2,452,232✔
1086
}
1087

1088
int fds_are_same_mount(int fd1, int fd2) {
2,452,302✔
1089
        STRUCT_NEW_STATX_DEFINE(st1);
2,452,302✔
1090
        STRUCT_NEW_STATX_DEFINE(st2);
2,452,302✔
1091
        int r;
2,452,302✔
1092

1093
        assert(fd1 >= 0);
2,452,302✔
1094
        assert(fd2 >= 0);
2,452,302✔
1095

1096
        r = statx_fallback(fd1, "", AT_EMPTY_PATH, STATX_TYPE|STATX_INO|STATX_MNT_ID, &st1.sx);
2,452,302✔
1097
        if (r < 0)
2,452,302✔
1098
                return r;
2,452,302✔
1099

1100
        r = statx_fallback(fd2, "", AT_EMPTY_PATH, STATX_TYPE|STATX_INO|STATX_MNT_ID, &st2.sx);
2,452,302✔
1101
        if (r < 0)
2,452,302✔
1102
                return r;
1103

1104
        /* First, compare inode. If these are different, the fd does not point to the root directory "/". */
1105
        if (!statx_inode_same(&st1.sx, &st2.sx))
2,452,302✔
1106
                return false;
1107

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

1112
        if (!FLAGS_SET(st1.nsx.stx_mask, STATX_MNT_ID)) {
2,130,555✔
1113
                int mntid;
×
1114

1115
                r = path_get_mnt_id_at_fallback(fd1, "", &mntid);
×
1116
                if (r < 0)
×
1117
                        return r;
×
1118
                assert(mntid >= 0);
×
1119

1120
                st1.nsx.stx_mnt_id = mntid;
×
UNCOV
1121
                st1.nsx.stx_mask |= STATX_MNT_ID;
×
1122
        }
1123

1124
        if (!FLAGS_SET(st2.nsx.stx_mask, STATX_MNT_ID)) {
2,130,555✔
UNCOV
1125
                int mntid;
×
1126

1127
                r = path_get_mnt_id_at_fallback(fd2, "", &mntid);
×
UNCOV
1128
                if (r < 0)
×
1129
                        return r;
×
1130
                assert(mntid >= 0);
×
1131

1132
                st2.nsx.stx_mnt_id = mntid;
×
UNCOV
1133
                st2.nsx.stx_mask |= STATX_MNT_ID;
×
1134
        }
1135

1136
        return statx_mount_same(&st1.nsx, &st2.nsx);
2,130,555✔
1137
}
1138

1139
const char* accmode_to_string(int flags) {
176✔
1140
        switch (flags & O_ACCMODE) {
176✔
1141
        case O_RDONLY:
1142
                return "ro";
1143
        case O_WRONLY:
3✔
1144
                return "wo";
3✔
1145
        case O_RDWR:
170✔
1146
                return "rw";
170✔
1147
        default:
×
1148
                return NULL;
×
1149
        }
1150
}
1151

1152
char* format_proc_pid_fd_path(char buf[static PROC_PID_FD_PATH_MAX], pid_t pid, int fd) {
1✔
1153
        assert(buf);
1✔
1154
        assert(fd >= 0);
1✔
1155
        assert(pid >= 0);
1✔
1156
        assert_se(snprintf_ok(buf, PROC_PID_FD_PATH_MAX, "/proc/" PID_FMT "/fd/%i", pid == 0 ? getpid_cached() : pid, fd));
1✔
1157
        return buf;
1✔
1158
}
1159

1160
int proc_fd_enoent_errno(void) {
7✔
1161
        int r;
7✔
1162

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

1167
        r = proc_mounted();
7✔
1168
        if (r == 0)
7✔
1169
                return -ENOSYS;  /* /proc/ is not available or not set up properly, we're most likely
1170
                                    in some chroot environment. */
1171
        if (r > 0)
7✔
1172
                return -EBADF;   /* If /proc/ is definitely around then this means the fd is not valid. */
7✔
1173

1174
        return -ENOENT;          /* Otherwise let's propagate the original ENOENT. */
1175
}
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