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

systemd / systemd / 17813902210

17 Sep 2025 11:56PM UTC coverage: 72.24% (-0.04%) from 72.281%
17813902210

push

github

web-flow
sysupdate: use conf_files_list_strv_full() where possible (#38198)

37 of 44 new or added lines in 1 file covered. (84.09%)

6236 existing lines in 79 files now uncovered.

302695 of 419015 relevant lines covered (72.24%)

1046897.1 hits per line

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

93.03
/src/basic/fileio.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <fcntl.h>
4
#include <stdio_ext.h>
5
#include <stdlib.h>
6
#include <sys/stat.h>
7
#include <unistd.h>
8

9
#include "alloc-util.h"
10
#include "errno-util.h"
11
#include "extract-word.h"
12
#include "fd-util.h"
13
#include "fileio.h"
14
#include "fs-util.h"
15
#include "hexdecoct.h"
16
#include "label.h"
17
#include "log.h"
18
#include "mkdir.h"
19
#include "nulstr-util.h"
20
#include "parse-util.h"
21
#include "path-util.h"
22
#include "socket-util.h"
23
#include "stat-util.h"
24
#include "stdio-util.h"
25
#include "string-util.h"
26
#include "strv.h"
27
#include "sync-util.h"
28
#include "terminal-util.h"
29
#include "time-util.h"
30
#include "tmpfile-util.h"
31

32
/* The maximum size of the file we'll read in one go in read_full_file() (64M). */
33
#define READ_FULL_BYTES_MAX (64U * U64_MB - UINT64_C(1))
34
/* Used when a size is specified for read_full_file() with READ_FULL_FILE_UNBASE64 or _UNHEX */
35
#define READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY 3
36

37
/* The maximum size of virtual files (i.e. procfs, sysfs, and other virtual "API" files) we'll read in one go
38
 * in read_virtual_file(). Note that this limit is different (and much lower) than the READ_FULL_BYTES_MAX
39
 * limit. This reflects the fact that we use different strategies for reading virtual and regular files:
40
 * virtual files we generally have to read in a single read() syscall since the kernel doesn't support
41
 * continuation read()s for them. Thankfully they are somewhat size constrained. Thus we can allocate the
42
 * full potential buffer in advance. Regular files OTOH can be much larger, and there we grow the allocations
43
 * exponentially in a loop. We use a size limit of 4M-2 because 4M-1 is the maximum buffer that /proc/sys/
44
 * allows us to read() (larger reads will fail with ENOMEM), and we want to read one extra byte so that we
45
 * can detect EOFs. */
46
#define READ_VIRTUAL_BYTES_MAX (4U * U64_MB - UINT64_C(2))
47

48
int fdopen_unlocked(int fd, const char *options, FILE **ret) {
335,718✔
49
        assert(ret);
335,718✔
50

51
        FILE *f = fdopen(fd, options);
335,718✔
52
        if (!f)
335,718✔
53
                return -errno;
×
54

55
        (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
335,718✔
56

57
        *ret = f;
335,718✔
58
        return 0;
335,718✔
59
}
60

61
int take_fdopen_unlocked(int *fd, const char *options, FILE **ret) {
335,718✔
62
        int r;
335,718✔
63

64
        assert(fd);
335,718✔
65

66
        r = fdopen_unlocked(*fd, options, ret);
335,718✔
67
        if (r < 0)
335,718✔
68
                return r;
69

70
        *fd = -EBADF;
335,718✔
71

72
        return 0;
335,718✔
73
}
74

75
FILE* take_fdopen(int *fd, const char *options) {
44,547✔
76
        assert(fd);
44,547✔
77

78
        FILE *f = fdopen(*fd, options);
44,547✔
79
        if (!f)
44,547✔
80
                return NULL;
81

82
        *fd = -EBADF;
44,547✔
83

84
        return f;
44,547✔
85
}
86

87
DIR* take_fdopendir(int *dfd) {
260,276✔
88
        assert(dfd);
260,276✔
89

90
        DIR *d = fdopendir(*dfd);
260,276✔
91
        if (!d)
260,276✔
92
                return NULL;
93

94
        *dfd = -EBADF;
260,276✔
95

96
        return d;
260,276✔
97
}
98

99
FILE* open_memstream_unlocked(char **ptr, size_t *sizeloc) {
731,682✔
100
        FILE *f = open_memstream(ptr, sizeloc);
731,682✔
101
        if (!f)
731,682✔
102
                return NULL;
103

104
        (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
731,682✔
105

106
        return f;
731,682✔
107
}
108

109
FILE* fmemopen_unlocked(void *buf, size_t size, const char *mode) {
121✔
110
        FILE *f = fmemopen(buf, size, mode);
121✔
111
        if (!f)
121✔
112
                return NULL;
113

114
        (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
121✔
115

116
        return f;
121✔
117
}
118

119
int write_string_stream_full(
157,762✔
120
                FILE *f,
121
                const char *line,
122
                WriteStringFileFlags flags,
123
                const struct timespec *ts) {
124

125
        bool needs_nl;
157,762✔
126
        int r, fd = -EBADF;
157,762✔
127

128
        assert(f);
157,762✔
129
        assert(line);
157,762✔
130

131
        if (ferror(f))
157,762✔
132
                return -EIO;
133

134
        if (ts) {
157,762✔
135
                /* If we shall set the timestamp we need the fd. But fmemopen() streams generally don't have
136
                 * an fd. Let's fail early in that case. */
137
                fd = fileno(f);
2✔
138
                if (fd < 0)
2✔
139
                        return -EBADF;
140
        }
141

142
        if (flags & WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) {
157,762✔
143
                _cleanup_free_ char *t = NULL;
8,800✔
144

145
                /* If value to be written is same as that of the existing value, then suppress the write. */
146

147
                if (fd < 0) {
8,800✔
148
                        fd = fileno(f);
8,800✔
149
                        if (fd < 0)
8,800✔
150
                                return -EBADF;
151
                }
152

153
                /* Read an additional byte to detect cases where the prefix matches but the rest
154
                 * doesn't. Also, 0 returned by read_virtual_file_fd() means the read was truncated and
155
                 * it won't be equal to the new value. */
156
                if (read_virtual_file_fd(fd, strlen(line)+1, &t, NULL) > 0 &&
17,409✔
157
                    streq_skip_trailing_chars(line, t, NEWLINE)) {
8,609✔
158
                        log_debug("No change in value '%s', suppressing write", line);
6,489✔
159
                        return 0;
6,489✔
160
                }
161

162
                if (lseek(fd, 0, SEEK_SET) < 0)
2,311✔
163
                        return -errno;
×
164
        }
165

166
        needs_nl = !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) && !endswith(line, "\n");
151,273✔
167

168
        if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) {
48,318✔
169
                /* If STDIO buffering was disabled, then let's append the newline character to the string
170
                 * itself, so that the write goes out in one go, instead of two */
171

172
                line = strjoina(line, "\n");
235,925✔
173
                needs_nl = false;
47,185✔
174
        }
175

176
        if (fputs(line, f) == EOF)
151,273✔
177
                return -errno;
8✔
178

179
        if (needs_nl)
151,265✔
180
                if (fputc('\n', f) == EOF)
1,132✔
181
                        return -errno;
×
182

183
        if (flags & WRITE_STRING_FILE_SYNC)
151,265✔
184
                r = fflush_sync_and_check(f);
1,710✔
185
        else
186
                r = fflush_and_check(f);
149,555✔
187
        if (r < 0)
151,265✔
188
                return r;
189

190
        if (ts) {
151,245✔
191
                const struct timespec twice[2] = {*ts, *ts};
2✔
192

193
                assert(fd >= 0);
2✔
194
                if (futimens(fd, twice) < 0)
2✔
195
                        return -errno;
×
196
        }
197

198
        return 0;
199
}
200

201
static mode_t write_string_file_flags_to_mode(WriteStringFileFlags flags) {
82,492✔
202

203
        /* We support three different modes, that are the ones that really make sense for text files like this:
204
         *
205
         *     → 0600 (i.e. root-only)
206
         *     → 0444 (i.e. read-only)
207
         *     → 0644 (i.e. writable for root, readable for everyone else)
208
         */
209

210
        return FLAGS_SET(flags, WRITE_STRING_FILE_MODE_0600) ? 0600 :
82,492✔
211
                FLAGS_SET(flags, WRITE_STRING_FILE_MODE_0444) ? 0444 : 0644;
82,258✔
212
}
213

214
static int write_string_file_atomic_at(
2,525✔
215
                int dir_fd,
216
                const char *fn,
217
                const char *line,
218
                WriteStringFileFlags flags,
219
                const struct timespec *ts) {
220

221
        _cleanup_fclose_ FILE *f = NULL;
2,525✔
222
        _cleanup_free_ char *p = NULL;
2,525✔
223
        int r;
2,525✔
224

225
        assert(fn);
2,525✔
226
        assert(line);
2,525✔
227

228
        /* Note that we'd really like to use O_TMPFILE here, but can't really, since we want replacement
229
         * semantics here, and O_TMPFILE can't offer that. i.e. rename() replaces but linkat() doesn't. */
230

231
        mode_t mode = write_string_file_flags_to_mode(flags);
2,525✔
232

233
        bool call_label_ops_post = false;
2,525✔
234
        if (FLAGS_SET(flags, WRITE_STRING_FILE_LABEL)) {
2,525✔
235
                r = label_ops_pre(dir_fd, fn, mode);
187✔
236
                if (r < 0)
187✔
237
                        return r;
238

239
                call_label_ops_post = true;
240
        }
241

242
        r = fopen_temporary_at(dir_fd, fn, &f, &p);
2,525✔
243
        int k = call_label_ops_post ? label_ops_post(f ? fileno(f) : dir_fd, f ? NULL : fn, /* created= */ !!f) : 0;
2,712✔
244
        /* If fopen_temporary_at() failed in the above, propagate the error code, and ignore failures in
245
         * label_ops_post(). */
246
        if (r < 0)
2,525✔
247
                return r;
248
        CLEANUP_TMPFILE_AT(dir_fd, p);
2,524✔
249
        if (k < 0)
2,524✔
250
                return k;
251

252
        r = write_string_stream_full(f, line, flags, ts);
2,524✔
253
        if (r < 0)
2,524✔
254
                return r;
255

256
        r = fchmod_umask(fileno(f), mode);
2,524✔
257
        if (r < 0)
2,524✔
258
                return r;
259

260
        r = RET_NERRNO(renameat(dir_fd, p, dir_fd, fn));
2,524✔
UNCOV
261
        if (r < 0)
×
262
                return r;
263

264
        p = mfree(p); /* disarm CLEANUP_TMPFILE_AT() */
2,524✔
265

266
        if (FLAGS_SET(flags, WRITE_STRING_FILE_SYNC)) {
2,524✔
267
                /* Sync the rename, too */
268
                r = fsync_directory_of_file(fileno(f));
1,710✔
269
                if (r < 0)
1,710✔
UNCOV
270
                        return r;
×
271
        }
272

273
        return 0;
274
}
275

276
int write_string_file_full(
138,708✔
277
                int dir_fd,
278
                const char *fn,
279
                const char *line,
280
                WriteStringFileFlags flags,
281
                const struct timespec *ts,
282
                const char *label_fn) {
283

284
        bool made_file = false;
138,708✔
285
        _cleanup_fclose_ FILE *f = NULL;
138,708✔
286
        _cleanup_close_ int fd = -EBADF;
138,708✔
287
        int r;
138,708✔
288

289
        assert(dir_fd == AT_FDCWD || dir_fd >= 0);
138,708✔
290
        assert(line);
138,708✔
291

292
        /* We don't know how to verify whether the file contents was already on-disk. */
293
        assert(!((flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE) && (flags & WRITE_STRING_FILE_SYNC)));
138,708✔
294

295
        if (flags & WRITE_STRING_FILE_MKDIR_0755) {
138,708✔
296
                assert(fn);
230✔
297

298
                r = mkdirat_parents(dir_fd, fn, 0755);
230✔
299
                if (r < 0)
230✔
300
                        return r;
301
        }
302

303
        if (flags & WRITE_STRING_FILE_ATOMIC) {
138,708✔
304
                assert(fn);
2,525✔
305
                assert(flags & WRITE_STRING_FILE_CREATE);
2,525✔
306

307
                r = write_string_file_atomic_at(dir_fd, fn, line, flags, ts);
2,525✔
308
                if (r < 0)
2,525✔
309
                        goto fail;
1✔
310

311
                return r;
312
        }
313

314
        /* We manually build our own version of fopen(..., "we") that works without O_CREAT and with O_NOFOLLOW if needed. */
315
        if (isempty(fn))
136,183✔
316
                r = fd = fd_reopen(
56,216✔
317
                                ASSERT_FD(dir_fd), O_CLOEXEC | O_NOCTTY |
56,216✔
318
                                (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
112,432✔
319
                                (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY) |
56,216✔
320
                                (FLAGS_SET(flags, WRITE_STRING_FILE_OPEN_NONBLOCKING) ? O_NONBLOCK : 0));
56,216✔
321
        else {
322
                mode_t mode = write_string_file_flags_to_mode(flags);
79,967✔
323
                bool call_label_ops_post = false;
79,967✔
324

325
                if (FLAGS_SET(flags, WRITE_STRING_FILE_LABEL|WRITE_STRING_FILE_CREATE)) {
79,967✔
326
                        r = label_ops_pre(dir_fd, label_fn ?: fn, mode);
379✔
327
                        if (r < 0)
379✔
UNCOV
328
                                goto fail;
×
329

330
                        call_label_ops_post = true;
331
                }
332

333
                r = fd = openat_report_new(
239,901✔
334
                                dir_fd, fn, O_CLOEXEC | O_NOCTTY |
79,967✔
335
                                (FLAGS_SET(flags, WRITE_STRING_FILE_NOFOLLOW) ? O_NOFOLLOW : 0) |
79,967✔
336
                                (FLAGS_SET(flags, WRITE_STRING_FILE_CREATE) ? O_CREAT : 0) |
79,967✔
337
                                (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
159,934✔
338
                                (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY) |
79,967✔
339
                                (FLAGS_SET(flags, WRITE_STRING_FILE_OPEN_NONBLOCKING) ? O_NONBLOCK : 0),
79,967✔
340
                                mode,
341
                                &made_file);
342
                if (call_label_ops_post)
79,967✔
343
                        /* If openat_report_new() failed in the above, propagate the error code, and ignore
344
                         * failures in label_ops_post(). */
345
                        RET_GATHER(r, label_ops_post(fd >= 0 ? fd : dir_fd, fd >= 0 ? NULL : fn, made_file));
1,137✔
346
        }
347
        if (r < 0)
136,183✔
348
                goto fail;
1,566✔
349

350
        r = take_fdopen_unlocked(&fd, "w", &f);
134,617✔
351
        if (r < 0)
134,617✔
UNCOV
352
                goto fail;
×
353

354
        if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
134,617✔
355
                setvbuf(f, NULL, _IONBF, 0);
133,458✔
356

357
        r = write_string_stream_full(f, line, flags, ts);
134,617✔
358
        if (r < 0)
134,617✔
359
                goto fail;
13✔
360

361
        return 0;
362

363
fail:
1,580✔
364
        if (made_file)
1,580✔
UNCOV
365
                (void) unlinkat(dir_fd, fn, 0);
×
366

367
        if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
1,580✔
368
                return r;
369

370
        f = safe_fclose(f);
1,549✔
371
        fd = safe_close(fd);
1,549✔
372

373
        /* OK, the operation failed, but let's see if the right contents in place already. If so, eat up the
374
         * error. */
375
        if (verify_file_at(dir_fd, fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) || (flags & WRITE_STRING_FILE_VERIFY_IGNORE_NEWLINE)) > 0)
1,551✔
376
                return 0;
470✔
377

378
        return r;
379
}
380

381
int write_string_filef(
253✔
382
                const char *fn,
383
                WriteStringFileFlags flags,
384
                const char *format, ...) {
385

386
        _cleanup_free_ char *p = NULL;
253✔
387
        va_list ap;
253✔
388
        int r;
253✔
389

390
        va_start(ap, format);
253✔
391
        r = vasprintf(&p, format, ap);
253✔
392
        va_end(ap);
253✔
393

394
        if (r < 0)
253✔
395
                return -ENOMEM;
396

397
        return write_string_file(fn, p, flags);
253✔
398
}
399

400
int write_base64_file_at(
7✔
401
                int dir_fd,
402
                const char *fn,
403
                const struct iovec *data,
404
                WriteStringFileFlags flags) {
405

406
        _cleanup_free_ char *encoded = NULL;
7✔
407
        ssize_t n;
7✔
408

409
        n = base64mem_full(data ? data->iov_base : NULL, data ? data->iov_len : 0, 79, &encoded);
7✔
410
        if (n < 0)
7✔
UNCOV
411
                return n;
×
412

413
        return write_string_file_at(dir_fd, fn, encoded, flags);
7✔
414
}
415

416
int read_one_line_file_at(int dir_fd, const char *filename, char **ret) {
156,041✔
417
        _cleanup_fclose_ FILE *f = NULL;
156,041✔
418
        int r;
156,041✔
419

420
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
156,041✔
421
        assert(filename);
156,041✔
422
        assert(ret);
156,041✔
423

424
        r = fopen_unlocked_at(dir_fd, filename, "re", 0, &f);
156,041✔
425
        if (r < 0)
156,041✔
426
                return r;
427

428
        return read_line(f, LONG_LINE_MAX, ret);
156,041✔
429
}
430

431
int verify_file_at(int dir_fd, const char *fn, const char *blob, bool accept_extra_nl) {
1,549✔
432
        _cleanup_fclose_ FILE *f = NULL;
1,549✔
433
        _cleanup_free_ char *buf = NULL;
1,549✔
434
        size_t l, k;
1,549✔
435
        int r;
1,549✔
436

437
        assert(blob);
1,549✔
438

439
        l = strlen(blob);
1,549✔
440

441
        if (accept_extra_nl && endswith(blob, "\n"))
1,549✔
442
                accept_extra_nl = false;
1✔
443

444
        buf = malloc(l + accept_extra_nl + 1);
1,549✔
445
        if (!buf)
1,549✔
446
                return -ENOMEM;
447

448
        r = fopen_unlocked_at(dir_fd, strempty(fn), "re", 0, &f);
1,549✔
449
        if (r < 0)
1,549✔
450
                return r;
451

452
        /* We try to read one byte more than we need, so that we know whether we hit eof */
453
        errno = 0;
881✔
454
        k = fread(buf, 1, l + accept_extra_nl + 1, f);
881✔
455
        if (ferror(f))
881✔
UNCOV
456
                return errno_or_else(EIO);
×
457

458
        if (k != l && k != l + accept_extra_nl)
881✔
459
                return 0;
460
        if (memcmp(buf, blob, l) != 0)
750✔
461
                return 0;
462
        if (k > l && buf[l] != '\n')
470✔
UNCOV
463
                return 0;
×
464

465
        return 1;
466
}
467

468
int read_virtual_file_at(
720,512✔
469
                int dir_fd,
470
                const char *filename,
471
                size_t max_size,
472
                char **ret_contents,
473
                size_t *ret_size) {
474

475
        _cleanup_free_ char *buf = NULL;
720,512✔
476
        size_t n, size;
720,512✔
477
        int n_retries;
720,512✔
478
        bool truncated = false;
720,512✔
479

480
        /* Virtual filesystems such as sysfs or procfs use kernfs, and kernfs can work with two sorts of
481
         * virtual files. One sort uses "seq_file", and the results of the first read are buffered for the
482
         * second read. The other sort uses "raw" reads which always go direct to the device. In the latter
483
         * case, the content of the virtual file must be retrieved with a single read otherwise a second read
484
         * might get the new value instead of finding EOF immediately. That's the reason why the usage of
485
         * fread(3) is prohibited in this case as it always performs a second call to read(2) looking for
486
         * EOF. See issue #13585.
487
         *
488
         * max_size specifies a limit on the bytes read. If max_size is SIZE_MAX, the full file is read. If
489
         * the full file is too large to read, an error is returned. For other values of max_size, *partial
490
         * contents* may be returned. (Though the read is still done using one syscall.) Returns 0 on
491
         * partial success, 1 if untruncated contents were read.
492
         *
493
         * Rule: for kernfs files using "seq_file" → use regular read_full_file_at()
494
         *       for kernfs files using "raw" → use read_virtual_file_at()
495
         */
496

497
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
720,512✔
498
        assert(max_size <= READ_VIRTUAL_BYTES_MAX || max_size == SIZE_MAX);
720,512✔
499

500
        _cleanup_close_ int fd = -EBADF;
720,512✔
501
        if (isempty(filename))
720,512✔
502
                fd = fd_reopen(ASSERT_FD(dir_fd), O_RDONLY | O_NOCTTY | O_CLOEXEC);
552,085✔
503
        else
504
                fd = RET_NERRNO(openat(dir_fd, filename, O_RDONLY | O_NOCTTY | O_CLOEXEC));
168,427✔
505
        if (fd < 0)
720,512✔
506
                return fd;
507

508
        /* Limit the number of attempts to read the number of bytes returned by fstat(). */
509
        n_retries = 3;
510

511
        for (;;) {
669,183✔
512
                struct stat st;
669,182✔
513

514
                if (fstat(fd, &st) < 0)
669,182✔
515
                        return -errno;
1,171✔
516

517
                if (!S_ISREG(st.st_mode))
669,182✔
518
                        return -EBADF;
519

520
                /* Be prepared for files from /proc which generally report a file size of 0. */
521
                assert_cc(READ_VIRTUAL_BYTES_MAX < SSIZE_MAX);
669,182✔
522
                if (st.st_size > 0 && n_retries > 1) {
669,182✔
523
                        /* Let's use the file size if we have more than 1 attempt left. On the last attempt
524
                         * we'll ignore the file size */
525

526
                        if (st.st_size > SSIZE_MAX) { /* Avoid overflow with 32-bit size_t and 64-bit off_t. */
498,279✔
527

528
                                if (max_size == SIZE_MAX)
529
                                        return -EFBIG;
530

531
                                size = max_size;
532
                        } else {
533
                                size = MIN((size_t) st.st_size, max_size);
498,279✔
534

535
                                if (size > READ_VIRTUAL_BYTES_MAX)
498,279✔
536
                                        return -EFBIG;
537
                        }
538

539
                        n_retries--;
498,279✔
540
                } else if (n_retries > 1) {
170,903✔
541
                        /* Files in /proc are generally smaller than the page size so let's start with
542
                         * a page size buffer from malloc and only use the max buffer on the final try. */
543
                        size = MIN3(page_size() - 1, READ_VIRTUAL_BYTES_MAX, max_size);
170,902✔
544
                        n_retries = 1;
170,902✔
545
                } else {
546
                        size = MIN(READ_VIRTUAL_BYTES_MAX, max_size);
1✔
547
                        n_retries = 0;
1✔
548
                }
549

550
                buf = malloc(size + 1);
669,182✔
551
                if (!buf)
669,182✔
552
                        return -ENOMEM;
553

554
                /* Use a bigger allocation if we got it anyway, but not more than the limit. */
555
                size = MIN3(MALLOC_SIZEOF_SAFE(buf) - 1, max_size, READ_VIRTUAL_BYTES_MAX);
669,182✔
556

557
                for (;;) {
669,182✔
558
                        ssize_t k;
669,182✔
559

560
                        /* Read one more byte so we can detect whether the content of the
561
                         * file has already changed or the guessed size for files from /proc
562
                         * wasn't large enough . */
563
                        k = read(fd, buf, size + 1);
669,182✔
564
                        if (k >= 0) {
669,182✔
565
                                n = k;
668,011✔
566
                                break;
668,011✔
567
                        }
568

569
                        if (errno != EINTR)
1,171✔
570
                                return -errno;
1,171✔
571
                }
572

573
                /* Consider a short read as EOF */
574
                if (n <= size)
668,011✔
575
                        break;
576

577
                /* If a maximum size is specified and we already read more we know the file is larger, and
578
                 * can handle this as truncation case. Note that if the size of what we read equals the
579
                 * maximum size then this doesn't mean truncation, the file might or might not end on that
580
                 * byte. We need to rerun the loop in that case, with a larger buffer size, so that we read
581
                 * at least one more byte to be able to distinguish EOF from truncation. */
582
                if (max_size != SIZE_MAX && n > max_size) {
36,892✔
583
                        n = size; /* Make sure we never use more than what we sized the buffer for (so that
584
                                   * we have one free byte in it for the trailing NUL we add below). */
585
                        truncated = true;
586
                        break;
587
                }
588

589
                /* We have no further attempts left? Then the file is apparently larger than our limits. Give up. */
590
                if (n_retries <= 0)
1✔
591
                        return -EFBIG;
592

593
                /* Hmm... either we read too few bytes from /proc or less likely the content of the file
594
                 * might have been changed (and is now bigger) while we were processing, let's try again
595
                 * either with the new file size. */
596

597
                if (lseek(fd, 0, SEEK_SET) < 0)
1✔
UNCOV
598
                        return -errno;
×
599

600
                buf = mfree(buf);
1✔
601
        }
602

603
        if (ret_contents) {
668,010✔
604

605
                /* Safety check: if the caller doesn't want to know the size of what we just read it will
606
                 * rely on the trailing NUL byte. But if there's an embedded NUL byte, then we should refuse
607
                 * operation as otherwise there'd be ambiguity about what we just read. */
608
                if (!ret_size && memchr(buf, 0, n))
631,374✔
609
                        return -EBADMSG;
610

611
                if (n < size) {
631,374✔
612
                        char *p;
622,995✔
613

614
                        /* Return rest of the buffer to libc */
615
                        p = realloc(buf, n + 1);
622,995✔
616
                        if (!p)
622,995✔
617
                                return -ENOMEM;
618
                        buf = p;
622,995✔
619
                }
620

621
                buf[n] = 0;
631,374✔
622
                *ret_contents = TAKE_PTR(buf);
631,374✔
623
        }
624

625
        if (ret_size)
668,010✔
626
                *ret_size = n;
512,232✔
627

628
        return !truncated;
668,010✔
629
}
630

631
int read_full_stream_full(
467,839✔
632
                FILE *f,
633
                const char *filename,
634
                uint64_t offset,
635
                size_t size,
636
                ReadFullFileFlags flags,
637
                char **ret_contents,
638
                size_t *ret_size) {
639

640
        _cleanup_free_ char *buf = NULL;
467,839✔
641
        size_t n, n_next = 0, l, expected_decoded_size = size;
467,839✔
642
        int fd, r;
467,839✔
643

644
        assert(f);
467,839✔
645
        assert(ret_contents);
467,839✔
646
        assert(!FLAGS_SET(flags, READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX));
467,839✔
647
        assert(size != SIZE_MAX || !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER));
467,839✔
648

649
        if (offset != UINT64_MAX && offset > LONG_MAX) /* fseek() can only deal with "long" offsets */
467,839✔
650
                return -ERANGE;
651

652
        if ((flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) != 0) {
467,839✔
653
                if (size <= SIZE_MAX / READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY)
34✔
654
                        size *= READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY;
32✔
655
                else
656
                        size = SIZE_MAX;
657
        }
658

659
        fd = fileno(f);
467,839✔
660
        if (fd >= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see
467,839✔
661
                        * fmemopen()), let's optimize our buffering */
662
                struct stat st;
467,731✔
663

664
                if (fstat(fd, &st) < 0)
467,731✔
UNCOV
665
                        return -errno;
×
666

667
                if (S_ISREG(st.st_mode)) {
467,731✔
668

669
                        /* Try to start with the right file size if we shall read the file in full. Note
670
                         * that we increase the size to read here by one, so that the first read attempt
671
                         * already makes us notice the EOF. If the reported size of the file is zero, we
672
                         * avoid this logic however, since quite likely it might be a virtual file in procfs
673
                         * that all report a zero file size. */
674

675
                        if (st.st_size > 0 &&
467,315✔
676
                            (size == SIZE_MAX || FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER))) {
1,260✔
677

678
                                uint64_t rsize =
1,337,691✔
679
                                        LESS_BY((uint64_t) st.st_size, offset == UINT64_MAX ? 0 : offset);
445,897✔
680

681
                                if (rsize < SIZE_MAX) /* overflow check */
445,897✔
682
                                        n_next = rsize + 1;
445,897✔
683
                        }
684

685
                        if (flags & READ_FULL_FILE_WARN_WORLD_READABLE)
467,315✔
686
                                (void) warn_file_is_world_accessible(filename, &st, NULL, 0);
127✔
687
                }
688
        }
689

690
        /* If we don't know how much to read, figure it out now. If we shall read a part of the file, then
691
         * allocate the requested size. If we shall load the full file start with LINE_MAX. Note that if
692
         * READ_FULL_FILE_FAIL_WHEN_LARGER we consider the specified size a safety limit, and thus also start
693
         * with LINE_MAX, under assumption the file is most likely much shorter. */
694
        if (n_next == 0)
467,731✔
695
                n_next = size != SIZE_MAX && !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) ? size : LINE_MAX;
21,942✔
696

697
        /* Never read more than we need to determine that our own limit is hit */
698
        if (n_next > READ_FULL_BYTES_MAX)
446,086✔
UNCOV
699
                n_next = READ_FULL_BYTES_MAX + 1;
×
700

701
        if (offset != UINT64_MAX && fseek(f, offset, SEEK_SET) < 0)
467,839✔
UNCOV
702
                return -errno;
×
703

704
        n = l = 0;
705
        for (;;) {
468,215✔
706
                char *t;
468,027✔
707
                size_t k;
468,027✔
708

709
                /* If we shall fail when reading overly large data, then read exactly one byte more than the
710
                 * specified size at max, since that'll tell us if there's anymore data beyond the limit. */
711
                if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && n_next > size)
468,027✔
712
                        n_next = size + 1;
8✔
713

714
                if (flags & READ_FULL_FILE_SECURE) {
468,027✔
715
                        t = malloc(n_next + 1);
1,510✔
716
                        if (!t) {
1,510✔
UNCOV
717
                                r = -ENOMEM;
×
718
                                goto finalize;
×
719
                        }
720
                        memcpy_safe(t, buf, n);
1,510✔
721
                        explicit_bzero_safe(buf, n);
1,510✔
722
                        free(buf);
1,510✔
723
                } else {
724
                        t = realloc(buf, n_next + 1);
466,517✔
725
                        if (!t)
466,517✔
726
                                return -ENOMEM;
727
                }
728

729
                buf = t;
468,027✔
730
                /* Unless a size has been explicitly specified, try to read as much as fits into the memory
731
                 * we allocated (minus 1, to leave one byte for the safety NUL byte) */
732
                n = size == SIZE_MAX ? MALLOC_SIZEOF_SAFE(buf) - 1 : n_next;
468,027✔
733

734
                errno = 0;
468,027✔
735
                k = fread(buf + l, 1, n - l, f);
468,027✔
736

737
                assert(k <= n - l);
468,027✔
738
                l += k;
468,027✔
739

740
                if (ferror(f)) {
468,027✔
741
                        r = errno_or_else(EIO);
2✔
742
                        goto finalize;
2✔
743
                }
744
                if (feof(f))
468,025✔
745
                        break;
746

747
                if (size != SIZE_MAX && !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER)) { /* If we got asked to read some specific size, we already sized the buffer right, hence leave */
283✔
748
                        assert(l == size);
89✔
749
                        break;
750
                }
751

752
                assert(k > 0); /* we can't have read zero bytes because that would have been EOF */
194✔
753

754
                if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && l > size) {
194✔
755
                        r = -E2BIG;
6✔
756
                        goto finalize;
6✔
757
                }
758

759
                if (n >= READ_FULL_BYTES_MAX) {
188✔
UNCOV
760
                        r = -E2BIG;
×
761
                        goto finalize;
×
762
                }
763

764
                n_next = MIN(n * 2, READ_FULL_BYTES_MAX);
188✔
765
        }
766

767
        if (flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) {
467,831✔
768
                _cleanup_free_ void *decoded = NULL;
32✔
769
                size_t decoded_size;
32✔
770

771
                buf[l++] = 0;
32✔
772
                if (flags & READ_FULL_FILE_UNBASE64)
32✔
773
                        r = unbase64mem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size);
30✔
774
                else
775
                        r = unhexmem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size);
2✔
776
                if (r < 0)
32✔
UNCOV
777
                        goto finalize;
×
778

779
                if (flags & READ_FULL_FILE_SECURE)
32✔
780
                        explicit_bzero_safe(buf, n);
14✔
781
                free_and_replace(buf, decoded);
32✔
782
                n = l = decoded_size;
32✔
783

784
                if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && l > expected_decoded_size) {
32✔
UNCOV
785
                        r = -E2BIG;
×
786
                        goto finalize;
×
787
                }
788
        }
789

790
        if (!ret_size) {
467,831✔
791
                /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
792
                 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
793
                 * there'd be ambiguity about what we just read. */
794

795
                if (memchr(buf, 0, l)) {
338,118✔
796
                        r = -EBADMSG;
2✔
797
                        goto finalize;
2✔
798
                }
799
        }
800

801
        buf[l] = 0;
467,829✔
802
        *ret_contents = TAKE_PTR(buf);
467,829✔
803

804
        if (ret_size)
467,829✔
805
                *ret_size = l;
129,713✔
806

807
        return 0;
808

809
finalize:
10✔
810
        if (flags & READ_FULL_FILE_SECURE)
10✔
811
                explicit_bzero_safe(buf, n);
3✔
812

813
        return r;
814
}
815

816
int read_full_file_full(
650,921✔
817
                int dir_fd,
818
                const char *filename,
819
                uint64_t offset,
820
                size_t size,
821
                ReadFullFileFlags flags,
822
                const char *bind_name,
823
                char **ret_contents,
824
                size_t *ret_size) {
825

826
        _cleanup_fclose_ FILE *f = NULL;
650,921✔
827
        XfopenFlags xflags = XFOPEN_UNLOCKED;
650,921✔
828
        int r;
650,921✔
829

830
        assert(filename);
650,921✔
831
        assert(ret_contents);
650,921✔
832

833
        if (FLAGS_SET(flags, READ_FULL_FILE_CONNECT_SOCKET) && /* If this is enabled, let's try to connect to it */
650,921✔
834
            offset == UINT64_MAX)                              /* Seeking is not supported on AF_UNIX sockets */
835
                xflags |= XFOPEN_SOCKET;
192✔
836

837
        r = xfopenat_full(dir_fd, filename, "re", 0, xflags, bind_name, &f);
650,921✔
838
        if (r < 0)
650,921✔
839
                return r;
840

841
        return read_full_stream_full(f, filename, offset, size, flags, ret_contents, ret_size);
452,455✔
842
}
843

844
int script_get_shebang_interpreter(const char *path, char **ret) {
8✔
845
        _cleanup_fclose_ FILE *f = NULL;
8✔
846
        int r;
8✔
847

848
        assert(path);
8✔
849

850
        f = fopen(path, "re");
8✔
851
        if (!f)
8✔
852
                return -errno;
1✔
853

854
        char c;
7✔
855
        r = safe_fgetc(f, &c);
7✔
856
        if (r < 0)
7✔
857
                return r;
858
        if (r == 0)
7✔
859
                return -EBADMSG;
860
        if (c != '#')
7✔
861
                return -EMEDIUMTYPE;
862
        r = safe_fgetc(f, &c);
2✔
863
        if (r < 0)
2✔
864
                return r;
865
        if (r == 0)
2✔
866
                return -EBADMSG;
867
        if (c != '!')
2✔
868
                return -EMEDIUMTYPE;
869

870
        _cleanup_free_ char *line = NULL;
2✔
871
        r = read_line(f, LONG_LINE_MAX, &line);
2✔
872
        if (r < 0)
2✔
873
                return r;
874

875
        _cleanup_free_ char *p = NULL;
2✔
876
        const char *s = line;
2✔
877

878
        r = extract_first_word(&s, &p, /* separators = */ NULL, /* flags = */ 0);
2✔
879
        if (r < 0)
2✔
880
                return r;
881
        if (r == 0)
2✔
882
                return -ENOEXEC;
883

884
        if (ret)
2✔
885
                *ret = TAKE_PTR(p);
2✔
886
        return 0;
887
}
888

889
int get_proc_field(const char *path, const char *key, char **ret) {
54,578✔
890
        _cleanup_fclose_ FILE *f = NULL;
54,578✔
891
        int r;
54,578✔
892

893
        /* Retrieve one field from a file like /proc/self/status. "key" matches the beginning of the line
894
         * and should not include whitespace or the delimiter (':').
895
         * Whitespaces after the ':' will be skipped. Only the first element is returned
896
         * (i.e. for /proc/meminfo line "MemTotal: 1024 kB" -> return "1024"). */
897

898
        assert(path);
54,578✔
899
        assert(key);
54,578✔
900

901
        r = fopen_unlocked(path, "re", &f);
54,578✔
902
        if (r == -ENOENT && proc_mounted() == 0)
54,578✔
903
                return -ENOSYS;
904
        if (r < 0)
54,564✔
905
                return r;
906

907
        for (;;) {
354,474✔
908
                 _cleanup_free_ char *line = NULL;
200,507✔
909

910
                 r = read_line(f, LONG_LINE_MAX, &line);
200,507✔
911
                 if (r < 0)
200,507✔
912
                         return r;
913
                 if (r == 0)
200,507✔
914
                         return -ENODATA;
915

916
                 char *l = startswith(line, key);
200,507✔
917
                 if (l && *l == ':') {
200,507✔
918
                         if (ret) {
46,540✔
919
                                 char *s = strdupcspn(skip_leading_chars(l + 1, " \t"), WHITESPACE);
46,540✔
920
                                 if (!s)
46,540✔
921
                                         return -ENOMEM;
922

923
                                 *ret = s;
46,540✔
924
                         }
925

926
                         return 0;
46,540✔
927
                 }
928
        }
929
}
930

931
DIR* xopendirat(int dir_fd, const char *name, int flags) {
223,849✔
932
        _cleanup_close_ int fd = -EBADF;
223,849✔
933

934
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
223,849✔
935
        assert(name);
223,849✔
936
        assert(!(flags & (O_CREAT|O_TMPFILE)));
223,849✔
937

938
        if (dir_fd == AT_FDCWD && flags == 0)
223,849✔
UNCOV
939
                return opendir(name);
×
940

941
        fd = openat(dir_fd, name, O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
223,849✔
942
        if (fd < 0)
223,849✔
943
                return NULL;
944

945
        return take_fdopendir(&fd);
223,358✔
946
}
947

948
int fopen_mode_to_flags(const char *mode) {
79,971✔
949
        const char *p;
79,971✔
950
        int flags;
79,971✔
951

952
        assert(mode);
79,971✔
953

954
        if ((p = startswith(mode, "r+")))
79,971✔
955
                flags = O_RDWR;
956
        else if ((p = startswith(mode, "r")))
79,970✔
957
                flags = O_RDONLY;
UNCOV
958
        else if ((p = startswith(mode, "w+")))
×
959
                flags = O_RDWR|O_CREAT|O_TRUNC;
UNCOV
960
        else if ((p = startswith(mode, "w")))
×
961
                flags = O_WRONLY|O_CREAT|O_TRUNC;
UNCOV
962
        else if ((p = startswith(mode, "a+")))
×
963
                flags = O_RDWR|O_CREAT|O_APPEND;
UNCOV
964
        else if ((p = startswith(mode, "a")))
×
965
                flags = O_WRONLY|O_CREAT|O_APPEND;
966
        else
967
                return -EINVAL;
968

969
        for (; *p != 0; p++) {
156,356✔
970

971
                switch (*p) {
76,385✔
972

973
                case 'e':
76,385✔
974
                        flags |= O_CLOEXEC;
76,385✔
975
                        break;
76,385✔
976

UNCOV
977
                case 'x':
×
978
                        flags |= O_EXCL;
×
979
                        break;
×
980

981
                case 'm':
982
                        /* ignore this here, fdopen() might care later though */
983
                        break;
984

985
                case 'c': /* not sure what to do about this one */
986
                default:
987
                        return -EINVAL;
988
                }
989
        }
990

991
        return flags;
992
}
993

994
static int xfopenat_regular(int dir_fd, const char *path, const char *mode, int open_flags, FILE **ret) {
909,653✔
995
        FILE *f;
909,653✔
996

997
        /* A combination of fopen() with openat() */
998

999
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
909,653✔
1000
        assert(path);
909,653✔
1001
        assert(mode);
909,653✔
1002
        assert(ret);
909,653✔
1003

1004
        if (dir_fd == AT_FDCWD && open_flags == 0)
909,653✔
1005
                f = fopen(path, mode);
908,728✔
1006
        else {
1007
                _cleanup_close_ int fd = -EBADF;
925✔
1008
                int mode_flags;
925✔
1009

1010
                mode_flags = fopen_mode_to_flags(mode);
925✔
1011
                if (mode_flags < 0)
925✔
1012
                        return mode_flags;
1013

1014
                fd = openat(dir_fd, path, mode_flags | open_flags);
925✔
1015
                if (fd < 0)
925✔
1016
                        return -errno;
371✔
1017

1018
                f = take_fdopen(&fd, mode);
554✔
1019
        }
1020
        if (!f)
909,282✔
1021
                return -errno;
233,255✔
1022

1023
        *ret = f;
676,027✔
1024
        return 0;
676,027✔
1025
}
1026

1027
static int xfopenat_unix_socket(int dir_fd, const char *path, const char *bind_name, FILE **ret) {
1✔
1028
        _cleanup_close_ int sk = -EBADF;
1✔
1029
        FILE *f;
1✔
1030
        int r;
1✔
1031

1032
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1✔
1033
        assert(path);
1✔
1034
        assert(ret);
1✔
1035

1036
        sk = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
1✔
1037
        if (sk < 0)
1✔
UNCOV
1038
                return -errno;
×
1039

1040
        if (bind_name) {
1✔
1041
                /* If the caller specified a socket name to bind to, do so before connecting. This is
1042
                 * useful to communicate some minor, short meta-information token from the client to
1043
                 * the server. */
1044
                union sockaddr_union bsa;
1✔
1045

1046
                r = sockaddr_un_set_path(&bsa.un, bind_name);
1✔
1047
                if (r < 0)
1✔
UNCOV
1048
                        return r;
×
1049

1050
                if (bind(sk, &bsa.sa, r) < 0)
1✔
UNCOV
1051
                        return -errno;
×
1052
        }
1053

1054
        r = connect_unix_path(sk, dir_fd, path);
1✔
1055
        if (r < 0)
1✔
1056
                return r;
1057

1058
        if (shutdown(sk, SHUT_WR) < 0)
1✔
UNCOV
1059
                return -errno;
×
1060

1061
        f = take_fdopen(&sk, "r");
1✔
1062
        if (!f)
1✔
UNCOV
1063
                return -errno;
×
1064

1065
        *ret = f;
1✔
1066
        return 0;
1✔
1067
}
1068

1069
int xfopenat_full(
909,653✔
1070
                int dir_fd,
1071
                const char *path,
1072
                const char *mode,
1073
                int open_flags,
1074
                XfopenFlags flags,
1075
                const char *bind_name,
1076
                FILE **ret) {
1077

1078
        FILE *f = NULL;  /* avoid false maybe-uninitialized warning */
909,653✔
1079
        int r;
909,653✔
1080

1081
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
909,653✔
1082
        assert(path);
909,653✔
1083
        assert(mode);
909,653✔
1084
        assert(ret);
909,653✔
1085

1086
        r = xfopenat_regular(dir_fd, path, mode, open_flags, &f);
909,653✔
1087
        if (r == -ENXIO && FLAGS_SET(flags, XFOPEN_SOCKET)) {
909,653✔
1088
                /* ENXIO is what Linux returns if we open a node that is an AF_UNIX socket */
1089
                r = xfopenat_unix_socket(dir_fd, path, bind_name, &f);
1✔
1090
                if (IN_SET(r, -ENOTSOCK, -EINVAL))
1✔
1091
                        return -ENXIO; /* propagate original error if this is not a socket after all */
909,653✔
1092
        }
1093
        if (r < 0)
909,653✔
1094
                return r;
1095

1096
        if (FLAGS_SET(flags, XFOPEN_UNLOCKED))
676,028✔
1097
                (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
675,788✔
1098

1099
        *ret = f;
676,028✔
1100
        return 0;
676,028✔
1101
}
1102

1103
int fdopen_independent(int fd, const char *mode, FILE **ret) {
11,267✔
1104
        _cleanup_close_ int copy_fd = -EBADF;
11,267✔
1105
        _cleanup_fclose_ FILE *f = NULL;
11,267✔
1106
        int mode_flags;
11,267✔
1107

1108
        assert(fd >= 0);
11,267✔
1109
        assert(mode);
11,267✔
1110
        assert(ret);
11,267✔
1111

1112
        /* A combination of fdopen() + fd_reopen(). i.e. reopens the inode the specified fd points to and
1113
         * returns a FILE* for it */
1114

1115
        mode_flags = fopen_mode_to_flags(mode);
11,267✔
1116
        if (mode_flags < 0)
11,267✔
1117
                return mode_flags;
1118

1119
        /* Flags returned by fopen_mode_to_flags might contain O_CREAT, but it doesn't make sense for fd_reopen
1120
         * since we're working on an existing fd anyway. Let's drop it here to avoid triggering assertion. */
1121
        copy_fd = fd_reopen(fd, mode_flags & ~O_CREAT);
11,267✔
1122
        if (copy_fd < 0)
11,267✔
1123
                return copy_fd;
1124

1125
        f = take_fdopen(&copy_fd, mode);
11,267✔
1126
        if (!f)
11,267✔
UNCOV
1127
                return -errno;
×
1128

1129
        *ret = TAKE_PTR(f);
11,267✔
1130
        return 0;
11,267✔
1131
}
1132

1133
static int search_and_open_internal(
29,504✔
1134
                const char *path,
1135
                int mode,            /* if ret_fd is NULL this is an [FRWX]_OK mode for access(), otherwise an open mode for open() */
1136
                const char *root,
1137
                char **search,
1138
                int *ret_fd,
1139
                char **ret_path) {
1140

1141
        int r;
29,504✔
1142

1143
        assert(!ret_fd || !FLAGS_SET(mode, O_CREAT)); /* We don't support O_CREAT for this */
29,504✔
1144
        assert(path);
29,504✔
1145

1146
        if (path_is_absolute(path)) {
29,504✔
UNCOV
1147
                _cleanup_close_ int fd = -EBADF;
×
1148

1149
                if (ret_fd)
5,580✔
1150
                        /* We only specify 0777 here to appease static analyzers, it's never used since we
1151
                         * don't support O_CREAT here */
1152
                        r = fd = RET_NERRNO(open(path, mode, 0777));
5,578✔
1153
                else
1154
                        r = RET_NERRNO(access(path, mode));
2✔
1155
                if (r < 0)
122✔
1156
                        return r;
1157

1158
                if (ret_path) {
5,458✔
1159
                        r = path_simplify_alloc(path, ret_path);
5,458✔
1160
                        if (r < 0)
5,458✔
1161
                                return r;
1162
                }
1163

1164
                if (ret_fd)
5,458✔
1165
                        *ret_fd = TAKE_FD(fd);
5,457✔
1166

1167
                return 0;
5,458✔
1168
        }
1169

1170
        if (!path_strv_resolve_uniq(search, root))
23,924✔
1171
                return -ENOMEM;
1172

1173
        STRV_FOREACH(i, search) {
133,285✔
1174
                _cleanup_close_ int fd = -EBADF;
138,865✔
1175
                _cleanup_free_ char *p = NULL;
111,338✔
1176

1177
                p = path_join(root, *i, path);
111,338✔
1178
                if (!p)
111,338✔
1179
                        return -ENOMEM;
1180

1181
                if (ret_fd)
111,338✔
1182
                        /* as above, 0777 is static analyzer appeasement */
1183
                        r = fd = RET_NERRNO(open(p, mode, 0777));
111,014✔
1184
                else
1185
                        r = RET_NERRNO(access(p, F_OK));
324✔
1186
                if (r >= 0) {
109,361✔
1187
                        if (ret_path)
1,977✔
1188
                                *ret_path = path_simplify(TAKE_PTR(p));
1,977✔
1189

1190
                        if (ret_fd)
1,977✔
1191
                                *ret_fd = TAKE_FD(fd);
1,970✔
1192

1193
                        return 0;
1,977✔
1194
                }
1195
                if (r != -ENOENT)
109,361✔
1196
                        return r;
1197
        }
1198

1199
        return -ENOENT;
1200
}
1201

1202
int search_and_open(
29,504✔
1203
                const char *path,
1204
                int mode,
1205
                const char *root,
1206
                char **search,
1207
                int *ret_fd,
1208
                char **ret_path) {
1209

1210
        _cleanup_strv_free_ char **copy = NULL;
29,504✔
1211

1212
        assert(path);
29,504✔
1213

1214
        copy = strv_copy((char**) search);
29,504✔
1215
        if (!copy)
29,504✔
1216
                return -ENOMEM;
1217

1218
        return search_and_open_internal(path, mode, root, copy, ret_fd, ret_path);
29,504✔
1219
}
1220

1221
static int search_and_fopen_internal(
29,499✔
1222
                const char *path,
1223
                const char *mode,
1224
                const char *root,
1225
                char **search,
1226
                FILE **ret_file,
1227
                char **ret_path) {
1228

1229
        _cleanup_free_ char *found_path = NULL;
29,499✔
1230
        _cleanup_close_ int fd = -EBADF;
29,499✔
1231
        int r;
29,499✔
1232

1233
        assert(path);
29,499✔
1234
        assert(mode || !ret_file);
29,499✔
1235

1236
        r = search_and_open(
59,105✔
1237
                        path,
1238
                        mode ? fopen_mode_to_flags(mode) : 0,
29,345✔
1239
                        root,
1240
                        search,
1241
                        ret_file ? &fd : NULL,
1242
                        ret_path ? &found_path : NULL);
1243
        if (r < 0)
29,499✔
1244
                return r;
1245

1246
        if (ret_file) {
7,430✔
1247
                FILE *f = take_fdopen(&fd, mode);
7,427✔
1248
                if (!f)
7,427✔
UNCOV
1249
                        return -errno;
×
1250

1251
                *ret_file = f;
7,427✔
1252
        }
1253

1254
        if (ret_path)
7,430✔
1255
                *ret_path = TAKE_PTR(found_path);
7,430✔
1256

1257
        return 0;
1258
}
1259

1260
int search_and_fopen(
5,583✔
1261
                const char *path,
1262
                const char *mode,
1263
                const char *root,
1264
                const char **search,
1265
                FILE **ret_file,
1266
                char **ret_path) {
1267

1268
        _cleanup_strv_free_ char **copy = NULL;
5,583✔
1269

1270
        assert(path);
5,583✔
1271
        assert(mode || !ret_file);
5,583✔
1272

1273
        copy = strv_copy((char**) search);
5,583✔
1274
        if (!copy)
5,583✔
1275
                return -ENOMEM;
1276

1277
        return search_and_fopen_internal(path, mode, root, copy, ret_file, ret_path);
5,583✔
1278
}
1279

1280
int search_and_fopen_nulstr(
23,916✔
1281
                const char *path,
1282
                const char *mode,
1283
                const char *root,
1284
                const char *search,
1285
                FILE **ret_file,
1286
                char **ret_path) {
1287

1288
        _cleanup_strv_free_ char **l = NULL;
23,916✔
1289

1290
        assert(path);
23,916✔
1291
        assert(mode || !ret_file);
23,916✔
1292

1293
        l = strv_split_nulstr(search);
23,916✔
1294
        if (!l)
23,916✔
1295
                return -ENOMEM;
1296

1297
        return search_and_fopen_internal(path, mode, root, l, ret_file, ret_path);
23,916✔
1298
}
1299

1300
int fflush_and_check(FILE *f) {
1,048,600✔
1301
        assert(f);
1,048,600✔
1302

1303
        errno = 0;
1,048,600✔
1304
        fflush(f);
1,048,600✔
1305

1306
        if (ferror(f))
1,048,600✔
1307
                return errno_or_else(EIO);
44✔
1308

1309
        return 0;
1310
}
1311

1312
int fflush_sync_and_check(FILE *f) {
2,145✔
1313
        int r, fd;
2,145✔
1314

1315
        assert(f);
2,145✔
1316

1317
        r = fflush_and_check(f);
2,145✔
1318
        if (r < 0)
2,145✔
1319
                return r;
1320

1321
        /* Not all file streams have an fd associated (think: fmemopen()), let's handle this gracefully and
1322
         * assume that in that case we need no explicit syncing */
1323
        fd = fileno(f);
2,145✔
1324
        if (fd < 0)
2,145✔
1325
                return 0;
1326

1327
        r = fsync_full(fd);
2,145✔
1328
        if (r < 0)
2,145✔
UNCOV
1329
                return r;
×
1330

1331
        return 0;
1332
}
1333

1334
int write_timestamp_file_atomic(const char *fn, usec_t n) {
200✔
1335
        char ln[DECIMAL_STR_MAX(n)+2];
200✔
1336

1337
        /* Creates a "timestamp" file, that contains nothing but a
1338
         * usec_t timestamp, formatted in ASCII. */
1339

1340
        if (!timestamp_is_set(n))
200✔
1341
                return -ERANGE;
200✔
1342

1343
        xsprintf(ln, USEC_FMT "\n", n);
200✔
1344

1345
        return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
200✔
1346
}
1347

1348
int read_timestamp_file(const char *fn, usec_t *ret) {
26✔
1349
        _cleanup_free_ char *ln = NULL;
26✔
1350
        uint64_t t;
26✔
1351
        int r;
26✔
1352

1353
        r = read_one_line_file(fn, &ln);
26✔
1354
        if (r < 0)
26✔
1355
                return r;
1356

UNCOV
1357
        r = safe_atou64(ln, &t);
×
1358
        if (r < 0)
×
1359
                return r;
1360

UNCOV
1361
        if (!timestamp_is_set(t))
×
1362
                return -ERANGE;
1363

UNCOV
1364
        *ret = (usec_t) t;
×
1365
        return 0;
×
1366
}
1367

1368
int fputs_with_separator(FILE *f, const char *s, const char *separator, bool *space) {
3,376✔
1369
        assert(s);
3,376✔
1370
        assert(space);
3,376✔
1371

1372
        /* Outputs the specified string with fputs(), but optionally prefixes it with a separator.
1373
         * The *space parameter when specified shall initially point to a boolean variable initialized
1374
         * to false. It is set to true after the first invocation. This call is supposed to be use in loops,
1375
         * where a separator shall be inserted between each element, but not before the first one. */
1376

1377
        if (!f)
3,376✔
UNCOV
1378
                f = stdout;
×
1379

1380
        if (!separator)
3,376✔
1381
                separator = " ";
1,670✔
1382

1383
        if (*space)
3,376✔
1384
                if (fputs(separator, f) < 0)
1,483✔
1385
                        return -EIO;
1386

1387
        *space = true;
3,376✔
1388

1389
        if (fputs(s, f) < 0)
3,376✔
UNCOV
1390
                return -EIO;
×
1391

1392
        return 0;
1393
}
1394

1395
int fputs_with_newline(FILE *f, const char *s) {
778✔
1396

1397
        /* This is like fputs() but outputs a trailing newline char, but only if the string isn't empty
1398
         * and doesn't end in a newline already. Returns 0 in case we didn't append a newline, > 0 otherwise. */
1399

1400
        if (isempty(s))
778✔
1401
                return 0;
1402

1403
        if (!f)
778✔
UNCOV
1404
                f = stdout;
×
1405

1406
        if (fputs(s, f) < 0)
778✔
1407
                return -EIO;
1408

1409
        if (endswith(s, "\n"))
778✔
1410
                return 0;
1411

1412
        if (fputc('\n', f) < 0)
625✔
UNCOV
1413
                return -EIO;
×
1414

1415
        return 1;
1416
}
1417

1418
/* A bitmask of the EOL markers we know */
1419
typedef enum EndOfLineMarker {
1420
        EOL_NONE     = 0,
1421
        EOL_ZERO     = 1 << 0,  /* \0 (aka NUL) */
1422
        EOL_TEN      = 1 << 1,  /* \n (aka NL, aka LF)  */
1423
        EOL_THIRTEEN = 1 << 2,  /* \r (aka CR)  */
1424
} EndOfLineMarker;
1425

1426
static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) {
198,877,187✔
1427

1428
        if (!FLAGS_SET(flags, READ_LINE_ONLY_NUL)) {
198,877,187✔
1429
                if (c == '\n')
198,093,076✔
1430
                        return EOL_TEN;
1431
                if (c == '\r')
191,548,805✔
1432
                        return EOL_THIRTEEN;
1433
        }
1434

1435
        if (c == '\0')
192,332,900✔
1436
                return EOL_ZERO;
24,555✔
1437

1438
        return EOL_NONE;
1439
}
1440

1441
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile, NULL);
6,130,370✔
1442

1443
int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) {
6,130,370✔
1444
        _cleanup_free_ char *buffer = NULL;
6,130,370✔
1445
        size_t n = 0, count = 0;
6,130,370✔
1446
        int r;
6,130,370✔
1447

1448
        assert(f);
6,130,370✔
1449

1450
        /* Something like a bounded version of getline().
1451
         *
1452
         * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
1453
         * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
1454
         * endings:
1455
         *
1456
         *     • \n        (UNIX)
1457
         *     • \r        (old MacOS)
1458
         *     • \0        (C strings)
1459
         *     • \n\0
1460
         *     • \r\0
1461
         *     • \r\n      (Windows)
1462
         *     • \n\r
1463
         *     • \r\n\0
1464
         *     • \n\r\0
1465
         *
1466
         * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1467
         * the number of characters in the returned string). When EOF is hit, 0 is returned.
1468
         *
1469
         * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1470
         * delimiters. If the limit is hit we fail and return -ENOBUFS.
1471
         *
1472
         * If a line shall be skipped ret may be initialized as NULL. */
1473

1474
        if (ret) {
6,130,370✔
1475
                if (!GREEDY_REALLOC(buffer, 1))
6,130,339✔
1476
                        return -ENOMEM;
1477
        }
1478

1479
        {
1480
                _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
6,130,370✔
1481
                EndOfLineMarker previous_eol = EOL_NONE;
6,130,370✔
1482
                flockfile(f);
6,130,370✔
1483

1484
                for (;;) {
199,316,713✔
1485
                        EndOfLineMarker eol;
199,316,713✔
1486
                        char c;
199,316,713✔
1487

1488
                        if (n >= limit)
199,316,713✔
1489
                                return -ENOBUFS;
14✔
1490

1491
                        if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */
199,316,707✔
1492
                                return -ENOBUFS;
1493

1494
                        r = safe_fgetc(f, &c);
199,316,707✔
1495
                        if (r < 0)
199,316,707✔
1496
                                return r;
1497
                        if (r == 0) /* EOF is definitely EOL */
199,316,699✔
1498
                                break;
1499

1500
                        eol = categorize_eol(c, flags);
198,877,187✔
1501

1502
                        if (FLAGS_SET(previous_eol, EOL_ZERO) ||
198,877,187✔
1503
                            (eol == EOL_NONE && previous_eol != EOL_NONE) ||
198,855,745✔
1504
                            (eol != EOL_NONE && (previous_eol & eol) != 0)) {
6,568,836✔
1505
                                /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
1506
                                 * EOL marker has been seen right before?  In either of these three cases we are
1507
                                 * done. But first, let's put this character back in the queue. (Note that we have to
1508
                                 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
1509
                                 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
1510
                                 * pass a negative value here. That said, to complicate things further ungetc() is
1511
                                 * actually happy with most negative characters and implicitly casts them back to
1512
                                 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
1513
                                 * godawful API!) */
1514
                                assert_se(ungetc((unsigned char) c, f) != EOF);
5,690,844✔
1515
                                break;
1516
                        }
1517

1518
                        count++;
193,186,343✔
1519

1520
                        if (eol != EOL_NONE) {
187,184,138✔
1521
                                /* If we are on a tty, we can't shouldn't wait for more input, because that
1522
                                 * generally means waiting for the user, interactively. In the case of a TTY
1523
                                 * we expect only \n as the single EOL marker, so we are in the lucky
1524
                                 * position that there is no need to wait. We check this condition last, to
1525
                                 * avoid isatty() check if not necessary. */
1526

1527
                                if ((flags & (READ_LINE_IS_A_TTY|READ_LINE_NOT_A_TTY)) == 0) {
6,002,205✔
1528
                                        int fd;
5,268,383✔
1529

1530
                                        fd = fileno(f);
5,268,383✔
1531
                                        if (fd < 0) /* Maybe an fmemopen() stream? Handle this gracefully,
5,268,383✔
1532
                                                     * and don't call isatty() on an invalid fd */
1533
                                                flags |= READ_LINE_NOT_A_TTY;
28✔
1534
                                        else
1535
                                                flags |= isatty_safe(fd) ? READ_LINE_IS_A_TTY : READ_LINE_NOT_A_TTY;
10,536,710✔
1536
                                }
1537
                                if (FLAGS_SET(flags, READ_LINE_IS_A_TTY))
6,002,205✔
1538
                                        break;
1539
                        }
1540

1541
                        if (eol != EOL_NONE) {
193,186,343✔
1542
                                previous_eol |= eol;
6,002,205✔
1543
                                continue;
6,002,205✔
1544
                        }
1545

1546
                        if (ret) {
187,184,138✔
1547
                                if (!GREEDY_REALLOC(buffer, n + 2))
187,184,038✔
1548
                                        return -ENOMEM;
1549

1550
                                buffer[n] = c;
187,184,038✔
1551
                        }
1552

1553
                        n++;
187,184,138✔
1554
                }
1555
        }
1556

1557
        if (ret) {
6,130,356✔
1558
                buffer[n] = 0;
6,130,325✔
1559

1560
                *ret = TAKE_PTR(buffer);
6,130,325✔
1561
        }
1562

1563
        return (int) count;
6,130,356✔
1564
}
1565

1566
int read_stripped_line(FILE *f, size_t limit, char **ret) {
2,560,999✔
1567
        _cleanup_free_ char *s = NULL;
2,560,999✔
1568
        int r, k;
2,560,999✔
1569

1570
        assert(f);
2,560,999✔
1571

1572
        r = read_line(f, limit, ret ? &s : NULL);
2,560,999✔
1573
        if (r < 0)
2,560,999✔
1574
                return r;
1575

1576
        if (ret) {
2,560,999✔
1577
                const char *p = strstrip(s);
2,560,999✔
1578
                if (p == s)
2,560,999✔
1579
                        *ret = TAKE_PTR(s);
2,560,996✔
1580
                else {
1581
                        k = strdup_to(ret, p);
3✔
1582
                        if (k < 0)
3✔
1583
                                return k;
1584
                }
1585
        }
1586

1587
        return r > 0;          /* Return 1 if something was read. */
2,560,999✔
1588
}
1589

1590
int safe_fgetc(FILE *f, char *ret) {
199,323,803✔
1591
        int k;
199,323,803✔
1592

1593
        assert(f);
199,323,803✔
1594

1595
        /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
1596
         * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
1597
         * has. */
1598

1599
        errno = 0;
199,323,803✔
1600
        k = fgetc(f);
199,323,803✔
1601
        if (k == EOF) {
199,323,803✔
1602
                if (ferror(f))
439,620✔
1603
                        return errno_or_else(EIO);
16✔
1604

1605
                if (ret)
439,612✔
1606
                        *ret = 0;
439,530✔
1607

1608
                return 0;
439,612✔
1609
        }
1610

1611
        if (ret)
198,884,183✔
1612
                *ret = k;
198,884,183✔
1613

1614
        return 1;
1615
}
1616

1617
int warn_file_is_world_accessible(const char *filename, struct stat *st, const char *unit, unsigned line) {
149✔
1618
        struct stat _st;
149✔
1619

1620
        if (!filename)
149✔
1621
                return 0;
149✔
1622

1623
        if (!st) {
149✔
1624
                if (stat(filename, &_st) < 0)
22✔
UNCOV
1625
                        return -errno;
×
1626
                st = &_st;
1627
        }
1628

1629
        if ((st->st_mode & S_IRWXO) == 0)
149✔
1630
                return 0;
1631

1632
        if (unit)
34✔
UNCOV
1633
                log_syntax(unit, LOG_WARNING, filename, line, 0,
×
1634
                           "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1635
                           filename, st->st_mode & 07777);
1636
        else
1637
                log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
34✔
1638
                            filename, st->st_mode & 07777);
1639
        return 0;
1640
}
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