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

systemd / systemd / 17872489626

19 Sep 2025 10:01PM UTC coverage: 72.323% (-0.003%) from 72.326%
17872489626

push

github

YHNdnzj
core/manager: honor show_status_overridden in manager_watch_jobs_next_time()

Prompted by #39029

1 of 1 new or added line in 1 file covered. (100.0%)

8275 existing lines in 112 files now uncovered.

302883 of 418794 relevant lines covered (72.32%)

1056411.46 hits per line

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

93.06
/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) {
341,305✔
49
        assert(ret);
341,305✔
50

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

55
        (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
341,305✔
56

57
        *ret = f;
341,305✔
58
        return 0;
341,305✔
59
}
60

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

64
        assert(fd);
341,305✔
65

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

70
        *fd = -EBADF;
341,305✔
71

72
        return 0;
341,305✔
73
}
74

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

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

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

84
        return f;
44,740✔
85
}
86

87
DIR* take_fdopendir(int *dfd) {
264,048✔
88
        assert(dfd);
264,048✔
89

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

94
        *dfd = -EBADF;
264,048✔
95

96
        return d;
264,048✔
97
}
98

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

104
        (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
732,350✔
105

106
        return f;
732,350✔
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(
160,688✔
120
                FILE *f,
121
                const char *line,
122
                WriteStringFileFlags flags,
123
                const struct timespec *ts) {
124

125
        bool needs_nl;
160,688✔
126
        int r, fd = -EBADF;
160,688✔
127

128
        assert(f);
160,688✔
129
        assert(line);
160,688✔
130

131
        if (ferror(f))
160,688✔
132
                return -EIO;
133

134
        if (ts) {
160,688✔
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) {
160,688✔
143
                _cleanup_free_ char *t = NULL;
8,854✔
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,854✔
148
                        fd = fileno(f);
8,854✔
149
                        if (fd < 0)
8,854✔
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,515✔
157
                    streq_skip_trailing_chars(line, t, NEWLINE)) {
8,661✔
158
                        log_debug("No change in value '%s', suppressing write", line);
6,497✔
159
                        return 0;
6,497✔
160
                }
161

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

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

168
        if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) {
49,095✔
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");
239,790✔
173
                needs_nl = false;
47,958✔
174
        }
175

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

179
        if (needs_nl)
154,183✔
180
                if (fputc('\n', f) == EOF)
1,136✔
181
                        return -errno;
×
182

183
        if (flags & WRITE_STRING_FILE_SYNC)
154,183✔
184
                r = fflush_sync_and_check(f);
1,710✔
185
        else
186
                r = fflush_and_check(f);
152,473✔
187
        if (r < 0)
154,183✔
188
                return r;
189

190
        if (ts) {
154,163✔
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) {
83,658✔
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 :
83,658✔
211
                FLAGS_SET(flags, WRITE_STRING_FILE_MODE_0444) ? 0444 : 0644;
83,423✔
212
}
213

214
static int write_string_file_atomic_at(
2,532✔
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,532✔
222
        _cleanup_free_ char *p = NULL;
2,532✔
223
        int r;
2,532✔
224

225
        assert(fn);
2,532✔
226
        assert(line);
2,532✔
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,532✔
232

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

239
                call_label_ops_post = true;
240
        }
241

242
        r = fopen_temporary_at(dir_fd, fn, &f, &p);
2,532✔
243
        int k = call_label_ops_post ? label_ops_post(f ? fileno(f) : dir_fd, f ? NULL : fn, /* created= */ !!f) : 0;
2,721✔
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,532✔
247
                return r;
248
        CLEANUP_TMPFILE_AT(dir_fd, p);
2,531✔
249
        if (k < 0)
2,531✔
250
                return k;
251

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

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

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

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

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

273
        return 0;
274
}
275

276
int write_string_file_full(
141,200✔
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;
141,200✔
285
        _cleanup_fclose_ FILE *f = NULL;
141,200✔
286
        _cleanup_close_ int fd = -EBADF;
141,200✔
287
        int r;
141,200✔
288

289
        assert(dir_fd == AT_FDCWD || dir_fd >= 0);
141,200✔
290
        assert(line);
141,200✔
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)));
141,200✔
294

295
        if (flags & WRITE_STRING_FILE_MKDIR_0755) {
141,200✔
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) {
141,200✔
304
                assert(fn);
2,532✔
305
                assert(flags & WRITE_STRING_FILE_CREATE);
2,532✔
306

307
                r = write_string_file_atomic_at(dir_fd, fn, line, flags, ts);
2,532✔
308
                if (r < 0)
2,532✔
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))
138,668✔
316
                r = fd = fd_reopen(
57,542✔
317
                                ASSERT_FD(dir_fd), O_CLOEXEC | O_NOCTTY |
57,542✔
318
                                (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
115,084✔
319
                                (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY) |
57,542✔
320
                                (FLAGS_SET(flags, WRITE_STRING_FILE_OPEN_NONBLOCKING) ? O_NONBLOCK : 0));
57,542✔
321
        else {
322
                mode_t mode = write_string_file_flags_to_mode(flags);
81,126✔
323
                bool call_label_ops_post = false;
81,126✔
324

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

330
                        call_label_ops_post = true;
331
                }
332

333
                r = fd = openat_report_new(
243,378✔
334
                                dir_fd, fn, O_CLOEXEC | O_NOCTTY |
81,126✔
335
                                (FLAGS_SET(flags, WRITE_STRING_FILE_NOFOLLOW) ? O_NOFOLLOW : 0) |
81,126✔
336
                                (FLAGS_SET(flags, WRITE_STRING_FILE_CREATE) ? O_CREAT : 0) |
81,126✔
337
                                (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
162,252✔
338
                                (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY) |
81,126✔
339
                                (FLAGS_SET(flags, WRITE_STRING_FILE_OPEN_NONBLOCKING) ? O_NONBLOCK : 0),
81,126✔
340
                                mode,
341
                                &made_file);
342
                if (call_label_ops_post)
81,126✔
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)
138,668✔
348
                goto fail;
1,584✔
349

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

354
        if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
137,084✔
355
                setvbuf(f, NULL, _IONBF, 0);
135,923✔
356

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

361
        return 0;
362

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

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

370
        f = safe_fclose(f);
1,567✔
371
        fd = safe_close(fd);
1,567✔
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,569✔
376
                return 0;
470✔
377

378
        return r;
379
}
380

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

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

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

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

397
        return write_string_file(fn, p, flags);
255✔
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✔
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) {
157,915✔
417
        _cleanup_fclose_ FILE *f = NULL;
157,915✔
418
        int r;
157,915✔
419

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

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

428
        return read_line(f, LONG_LINE_MAX, ret);
157,915✔
429
}
430

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

437
        assert(blob);
1,567✔
438

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

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

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

448
        r = fopen_unlocked_at(dir_fd, strempty(fn), "re", 0, &f);
1,567✔
449
        if (r < 0)
1,567✔
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✔
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✔
463
                return 0;
×
464

465
        return 1;
466
}
467

468
int read_virtual_file_at(
734,770✔
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;
734,770✔
476
        size_t n, size;
734,770✔
477
        int n_retries;
734,770✔
478
        bool truncated = false;
734,770✔
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);
734,770✔
498
        assert(max_size <= READ_VIRTUAL_BYTES_MAX || max_size == SIZE_MAX);
734,770✔
499

500
        _cleanup_close_ int fd = -EBADF;
734,770✔
501
        if (isempty(filename))
734,770✔
502
                fd = fd_reopen(ASSERT_FD(dir_fd), O_RDONLY | O_NOCTTY | O_CLOEXEC);
563,803✔
503
        else
504
                fd = RET_NERRNO(openat(dir_fd, filename, O_RDONLY | O_NOCTTY | O_CLOEXEC));
170,967✔
505
        if (fd < 0)
734,770✔
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 (;;) {
682,588✔
512
                struct stat st;
682,587✔
513

514
                if (fstat(fd, &st) < 0)
682,587✔
515
                        return -errno;
1,174✔
516

517
                if (!S_ISREG(st.st_mode))
682,587✔
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);
682,587✔
522
                if (st.st_size > 0 && n_retries > 1) {
682,587✔
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. */
509,024✔
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);
509,024✔
534

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

539
                        n_retries--;
509,024✔
540
                } else if (n_retries > 1) {
173,563✔
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);
173,562✔
544
                        n_retries = 1;
173,562✔
545
                } else {
546
                        size = MIN(READ_VIRTUAL_BYTES_MAX, max_size);
1✔
547
                        n_retries = 0;
1✔
548
                }
549

550
                buf = malloc(size + 1);
682,587✔
551
                if (!buf)
682,587✔
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);
682,587✔
556

557
                for (;;) {
682,587✔
558
                        ssize_t k;
682,587✔
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);
682,587✔
564
                        if (k >= 0) {
682,587✔
565
                                n = k;
681,413✔
566
                                break;
681,413✔
567
                        }
568

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

573
                /* Consider a short read as EOF */
574
                if (n <= size)
681,413✔
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) {
37,350✔
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✔
598
                        return -errno;
×
599

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

603
        if (ret_contents) {
681,412✔
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))
644,320✔
609
                        return -EBADMSG;
610

611
                if (n < size) {
644,320✔
612
                        char *p;
635,906✔
613

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

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

625
        if (ret_size)
681,412✔
626
                *ret_size = n;
523,115✔
627

628
        return !truncated;
681,412✔
629
}
630

631
int read_full_stream_full(
479,010✔
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;
479,010✔
641
        size_t n, n_next = 0, l, expected_decoded_size = size;
479,010✔
642
        int fd, r;
479,010✔
643

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

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

652
        if ((flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) != 0) {
479,010✔
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);
479,010✔
660
        if (fd >= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see
479,010✔
661
                        * fmemopen()), let's optimize our buffering */
662
                struct stat st;
478,902✔
663

664
                if (fstat(fd, &st) < 0)
478,902✔
665
                        return -errno;
×
666

667
                if (S_ISREG(st.st_mode)) {
478,902✔
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 &&
478,490✔
676
                            (size == SIZE_MAX || FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER))) {
1,284✔
677

678
                                uint64_t rsize =
1,369,680✔
679
                                        LESS_BY((uint64_t) st.st_size, offset == UINT64_MAX ? 0 : offset);
456,560✔
680

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

685
                        if (flags & READ_FULL_FILE_WARN_WORLD_READABLE)
478,490✔
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)
478,902✔
695
                n_next = size != SIZE_MAX && !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) ? size : LINE_MAX;
22,450✔
696

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

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

704
        n = l = 0;
705
        for (;;) {
479,386✔
706
                char *t;
479,198✔
707
                size_t k;
479,198✔
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)
479,198✔
712
                        n_next = size + 1;
8✔
713

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

729
                buf = t;
479,198✔
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;
479,198✔
733

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

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

740
                if (ferror(f)) {
479,198✔
741
                        r = errno_or_else(EIO);
2✔
742
                        goto finalize;
2✔
743
                }
744
                if (feof(f))
479,196✔
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 */
285✔
748
                        assert(l == size);
91✔
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✔
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)) {
479,002✔
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✔
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✔
785
                        r = -E2BIG;
×
786
                        goto finalize;
×
787
                }
788
        }
789

790
        if (!ret_size) {
479,002✔
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)) {
347,757✔
796
                        r = -EBADMSG;
2✔
797
                        goto finalize;
2✔
798
                }
799
        }
800

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

804
        if (ret_size)
479,000✔
805
                *ret_size = l;
131,245✔
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(
668,459✔
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;
668,459✔
827
        XfopenFlags xflags = XFOPEN_UNLOCKED;
668,459✔
828
        int r;
668,459✔
829

830
        assert(filename);
668,459✔
831
        assert(ret_contents);
668,459✔
832

833
        if (FLAGS_SET(flags, READ_FULL_FILE_CONNECT_SOCKET) && /* If this is enabled, let's try to connect to it */
668,459✔
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);
668,459✔
838
        if (r < 0)
668,459✔
839
                return r;
840

841
        return read_full_stream_full(f, filename, offset, size, flags, ret_contents, ret_size);
463,722✔
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) {
51,759✔
890
        _cleanup_fclose_ FILE *f = NULL;
51,759✔
891
        int r;
51,759✔
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);
51,759✔
899
        assert(key);
51,759✔
900

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

907
        for (;;) {
331,518✔
908
                 _cleanup_free_ char *line = NULL;
187,768✔
909

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

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

923
                                 *ret = s;
44,018✔
924
                         }
925

926
                         return 0;
44,018✔
927
                 }
928
        }
929
}
930

931
DIR* xopendirat(int dir_fd, const char *path, int flags) {
227,622✔
932
        _cleanup_close_ int fd = -EBADF;
227,622✔
933

934
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
227,622✔
935
        assert(!(flags & (O_CREAT|O_TMPFILE)));
227,622✔
936

937
        if ((dir_fd == AT_FDCWD || path_is_absolute(path)) &&
227,991✔
938
            (flags &~ O_DIRECTORY) == 0)
1,520✔
939
                return opendir(path);
×
940

941
        if (isempty(path)) {
227,622✔
942
                path = ".";
225,733✔
943
                flags |= O_NOFOLLOW;
225,733✔
944
        }
945

946
        fd = openat(dir_fd, path, O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
227,622✔
947
        if (fd < 0)
227,622✔
948
                return NULL;
949

950
        return take_fdopendir(&fd);
227,123✔
951
}
952

953
int fopen_mode_to_flags(const char *mode) {
79,674✔
954
        const char *p;
79,674✔
955
        int flags;
79,674✔
956

957
        assert(mode);
79,674✔
958

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

974
        for (; *p != 0; p++) {
155,762✔
975

976
                switch (*p) {
76,088✔
977

978
                case 'e':
76,088✔
979
                        flags |= O_CLOEXEC;
76,088✔
980
                        break;
76,088✔
981

UNCOV
982
                case 'x':
×
UNCOV
983
                        flags |= O_EXCL;
×
UNCOV
984
                        break;
×
985

986
                case 'm':
987
                        /* ignore this here, fdopen() might care later though */
988
                        break;
989

990
                case 'c': /* not sure what to do about this one */
991
                default:
992
                        return -EINVAL;
993
                }
994
        }
995

996
        return flags;
997
}
998

999
static int xfopenat_regular(int dir_fd, const char *path, const char *mode, int open_flags, FILE **ret) {
926,693✔
1000
        FILE *f;
926,693✔
1001

1002
        /* A combination of fopen() with openat() */
1003

1004
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
926,693✔
1005
        assert(path);
926,693✔
1006
        assert(mode);
926,693✔
1007
        assert(ret);
926,693✔
1008

1009
        if (dir_fd == AT_FDCWD && open_flags == 0)
926,693✔
1010
                f = fopen(path, mode);
925,770✔
1011
        else {
1012
                _cleanup_close_ int fd = -EBADF;
923✔
1013
                int mode_flags;
923✔
1014

1015
                mode_flags = fopen_mode_to_flags(mode);
923✔
1016
                if (mode_flags < 0)
923✔
1017
                        return mode_flags;
1018

1019
                fd = openat(dir_fd, path, mode_flags | open_flags);
923✔
1020
                if (fd < 0)
923✔
1021
                        return -errno;
362✔
1022

1023
                f = take_fdopen(&fd, mode);
561✔
1024
        }
1025
        if (!f)
926,331✔
1026
                return -errno;
239,720✔
1027

1028
        *ret = f;
686,611✔
1029
        return 0;
686,611✔
1030
}
1031

1032
static int xfopenat_unix_socket(int dir_fd, const char *path, const char *bind_name, FILE **ret) {
1✔
1033
        _cleanup_close_ int sk = -EBADF;
1✔
1034
        FILE *f;
1✔
1035
        int r;
1✔
1036

1037
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1✔
1038
        assert(path);
1✔
1039
        assert(ret);
1✔
1040

1041
        sk = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
1✔
1042
        if (sk < 0)
1✔
UNCOV
1043
                return -errno;
×
1044

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

1051
                r = sockaddr_un_set_path(&bsa.un, bind_name);
1✔
1052
                if (r < 0)
1✔
UNCOV
1053
                        return r;
×
1054

1055
                if (bind(sk, &bsa.sa, r) < 0)
1✔
UNCOV
1056
                        return -errno;
×
1057
        }
1058

1059
        r = connect_unix_path(sk, dir_fd, path);
1✔
1060
        if (r < 0)
1✔
1061
                return r;
1062

1063
        if (shutdown(sk, SHUT_WR) < 0)
1✔
UNCOV
1064
                return -errno;
×
1065

1066
        f = take_fdopen(&sk, "r");
1✔
1067
        if (!f)
1✔
UNCOV
1068
                return -errno;
×
1069

1070
        *ret = f;
1✔
1071
        return 0;
1✔
1072
}
1073

1074
int xfopenat_full(
926,693✔
1075
                int dir_fd,
1076
                const char *path,
1077
                const char *mode,
1078
                int open_flags,
1079
                XfopenFlags flags,
1080
                const char *bind_name,
1081
                FILE **ret) {
1082

1083
        FILE *f = NULL;  /* avoid false maybe-uninitialized warning */
926,693✔
1084
        int r;
926,693✔
1085

1086
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
926,693✔
1087
        assert(path);
926,693✔
1088
        assert(mode);
926,693✔
1089
        assert(ret);
926,693✔
1090

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

1101
        if (FLAGS_SET(flags, XFOPEN_UNLOCKED))
686,612✔
1102
                (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
686,370✔
1103

1104
        *ret = f;
686,612✔
1105
        return 0;
686,612✔
1106
}
1107

1108
int fdopen_independent(int fd, const char *mode, FILE **ret) {
11,266✔
1109
        _cleanup_close_ int copy_fd = -EBADF;
11,266✔
1110
        _cleanup_fclose_ FILE *f = NULL;
11,266✔
1111
        int mode_flags;
11,266✔
1112

1113
        assert(fd >= 0);
11,266✔
1114
        assert(mode);
11,266✔
1115
        assert(ret);
11,266✔
1116

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

1120
        mode_flags = fopen_mode_to_flags(mode);
11,266✔
1121
        if (mode_flags < 0)
11,266✔
1122
                return mode_flags;
1123

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

1130
        f = take_fdopen(&copy_fd, mode);
11,266✔
1131
        if (!f)
11,266✔
UNCOV
1132
                return -errno;
×
1133

1134
        *ret = TAKE_PTR(f);
11,266✔
1135
        return 0;
11,266✔
1136
}
1137

1138
static int search_and_open_internal(
29,107✔
1139
                const char *path,
1140
                int mode,            /* if ret_fd is NULL this is an [FRWX]_OK mode for access(), otherwise an open mode for open() */
1141
                const char *root,
1142
                char **search,
1143
                int *ret_fd,
1144
                char **ret_path) {
1145

1146
        int r;
29,107✔
1147

1148
        assert(!ret_fd || !FLAGS_SET(mode, O_CREAT)); /* We don't support O_CREAT for this */
29,107✔
1149
        assert(path);
29,107✔
1150

1151
        if (path_is_absolute(path)) {
29,107✔
UNCOV
1152
                _cleanup_close_ int fd = -EBADF;
×
1153

1154
                if (ret_fd)
5,594✔
1155
                        /* We only specify 0777 here to appease static analyzers, it's never used since we
1156
                         * don't support O_CREAT here */
1157
                        r = fd = RET_NERRNO(open(path, mode, 0777));
5,592✔
1158
                else
1159
                        r = RET_NERRNO(access(path, mode));
2✔
1160
                if (r < 0)
124✔
1161
                        return r;
1162

1163
                if (ret_path) {
5,470✔
1164
                        r = path_simplify_alloc(path, ret_path);
5,470✔
1165
                        if (r < 0)
5,470✔
1166
                                return r;
1167
                }
1168

1169
                if (ret_fd)
5,470✔
1170
                        *ret_fd = TAKE_FD(fd);
5,469✔
1171

1172
                return 0;
5,470✔
1173
        }
1174

1175
        if (!path_strv_resolve_uniq(search, root))
23,513✔
1176
                return -ENOMEM;
1177

1178
        STRV_FOREACH(i, search) {
131,304✔
1179
                _cleanup_close_ int fd = -EBADF;
136,898✔
1180
                _cleanup_free_ char *p = NULL;
109,671✔
1181

1182
                p = path_join(root, *i, path);
109,671✔
1183
                if (!p)
109,671✔
1184
                        return -ENOMEM;
1185

1186
                if (ret_fd)
109,671✔
1187
                        /* as above, 0777 is static analyzer appeasement */
1188
                        r = fd = RET_NERRNO(open(p, mode, 0777));
109,347✔
1189
                else
1190
                        r = RET_NERRNO(access(p, F_OK));
324✔
1191
                if (r >= 0) {
107,791✔
1192
                        if (ret_path)
1,880✔
1193
                                *ret_path = path_simplify(TAKE_PTR(p));
1,880✔
1194

1195
                        if (ret_fd)
1,880✔
1196
                                *ret_fd = TAKE_FD(fd);
1,873✔
1197

1198
                        return 0;
1,880✔
1199
                }
1200
                if (r != -ENOENT)
107,791✔
1201
                        return r;
1202
        }
1203

1204
        return -ENOENT;
1205
}
1206

1207
int search_and_open(
29,107✔
1208
                const char *path,
1209
                int mode,
1210
                const char *root,
1211
                char **search,
1212
                int *ret_fd,
1213
                char **ret_path) {
1214

1215
        _cleanup_strv_free_ char **copy = NULL;
29,107✔
1216

1217
        assert(path);
29,107✔
1218

1219
        copy = strv_copy((char**) search);
29,107✔
1220
        if (!copy)
29,107✔
1221
                return -ENOMEM;
1222

1223
        return search_and_open_internal(path, mode, root, copy, ret_fd, ret_path);
29,107✔
1224
}
1225

1226
static int search_and_fopen_internal(
29,102✔
1227
                const char *path,
1228
                const char *mode,
1229
                const char *root,
1230
                char **search,
1231
                FILE **ret_file,
1232
                char **ret_path) {
1233

1234
        _cleanup_free_ char *found_path = NULL;
29,102✔
1235
        _cleanup_close_ int fd = -EBADF;
29,102✔
1236
        int r;
29,102✔
1237

1238
        assert(path);
29,102✔
1239
        assert(mode || !ret_file);
29,102✔
1240

1241
        r = search_and_open(
58,313✔
1242
                        path,
1243
                        mode ? fopen_mode_to_flags(mode) : 0,
28,948✔
1244
                        root,
1245
                        search,
1246
                        ret_file ? &fd : NULL,
1247
                        ret_path ? &found_path : NULL);
1248
        if (r < 0)
29,102✔
1249
                return r;
1250

1251
        if (ret_file) {
7,345✔
1252
                FILE *f = take_fdopen(&fd, mode);
7,342✔
1253
                if (!f)
7,342✔
UNCOV
1254
                        return -errno;
×
1255

1256
                *ret_file = f;
7,342✔
1257
        }
1258

1259
        if (ret_path)
7,345✔
1260
                *ret_path = TAKE_PTR(found_path);
7,345✔
1261

1262
        return 0;
1263
}
1264

1265
int search_and_fopen(
5,595✔
1266
                const char *path,
1267
                const char *mode,
1268
                const char *root,
1269
                const char **search,
1270
                FILE **ret_file,
1271
                char **ret_path) {
1272

1273
        _cleanup_strv_free_ char **copy = NULL;
5,595✔
1274

1275
        assert(path);
5,595✔
1276
        assert(mode || !ret_file);
5,595✔
1277

1278
        copy = strv_copy((char**) search);
5,595✔
1279
        if (!copy)
5,595✔
1280
                return -ENOMEM;
1281

1282
        return search_and_fopen_internal(path, mode, root, copy, ret_file, ret_path);
5,595✔
1283
}
1284

1285
int search_and_fopen_nulstr(
23,507✔
1286
                const char *path,
1287
                const char *mode,
1288
                const char *root,
1289
                const char *search,
1290
                FILE **ret_file,
1291
                char **ret_path) {
1292

1293
        _cleanup_strv_free_ char **l = NULL;
23,507✔
1294

1295
        assert(path);
23,507✔
1296
        assert(mode || !ret_file);
23,507✔
1297

1298
        l = strv_split_nulstr(search);
23,507✔
1299
        if (!l)
23,507✔
1300
                return -ENOMEM;
1301

1302
        return search_and_fopen_internal(path, mode, root, l, ret_file, ret_path);
23,507✔
1303
}
1304

1305
int fflush_and_check(FILE *f) {
1,055,295✔
1306
        assert(f);
1,055,295✔
1307

1308
        errno = 0;
1,055,295✔
1309
        fflush(f);
1,055,295✔
1310

1311
        if (ferror(f))
1,055,295✔
1312
                return errno_or_else(EIO);
46✔
1313

1314
        return 0;
1315
}
1316

1317
int fflush_sync_and_check(FILE *f) {
2,145✔
1318
        int r, fd;
2,145✔
1319

1320
        assert(f);
2,145✔
1321

1322
        r = fflush_and_check(f);
2,145✔
1323
        if (r < 0)
2,145✔
1324
                return r;
1325

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

1332
        r = fsync_full(fd);
2,145✔
1333
        if (r < 0)
2,145✔
UNCOV
1334
                return r;
×
1335

1336
        return 0;
1337
}
1338

1339
int write_timestamp_file_atomic(const char *fn, usec_t n) {
200✔
1340
        char ln[DECIMAL_STR_MAX(n)+2];
200✔
1341

1342
        /* Creates a "timestamp" file, that contains nothing but a
1343
         * usec_t timestamp, formatted in ASCII. */
1344

1345
        if (!timestamp_is_set(n))
200✔
1346
                return -ERANGE;
200✔
1347

1348
        xsprintf(ln, USEC_FMT "\n", n);
200✔
1349

1350
        return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
200✔
1351
}
1352

1353
int read_timestamp_file(const char *fn, usec_t *ret) {
27✔
1354
        _cleanup_free_ char *ln = NULL;
27✔
1355
        uint64_t t;
27✔
1356
        int r;
27✔
1357

1358
        r = read_one_line_file(fn, &ln);
27✔
1359
        if (r < 0)
27✔
1360
                return r;
1361

UNCOV
1362
        r = safe_atou64(ln, &t);
×
UNCOV
1363
        if (r < 0)
×
1364
                return r;
1365

UNCOV
1366
        if (!timestamp_is_set(t))
×
1367
                return -ERANGE;
1368

UNCOV
1369
        *ret = (usec_t) t;
×
UNCOV
1370
        return 0;
×
1371
}
1372

1373
int fputs_with_separator(FILE *f, const char *s, const char *separator, bool *space) {
3,406✔
1374
        assert(s);
3,406✔
1375
        assert(space);
3,406✔
1376

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

1382
        if (!f)
3,406✔
UNCOV
1383
                f = stdout;
×
1384

1385
        if (!separator)
3,406✔
1386
                separator = " ";
1,711✔
1387

1388
        if (*space)
3,406✔
1389
                if (fputs(separator, f) < 0)
1,505✔
1390
                        return -EIO;
1391

1392
        *space = true;
3,406✔
1393

1394
        if (fputs(s, f) < 0)
3,406✔
UNCOV
1395
                return -EIO;
×
1396

1397
        return 0;
1398
}
1399

1400
int fputs_with_newline(FILE *f, const char *s) {
789✔
1401

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

1405
        if (isempty(s))
789✔
1406
                return 0;
1407

1408
        if (!f)
789✔
UNCOV
1409
                f = stdout;
×
1410

1411
        if (fputs(s, f) < 0)
789✔
1412
                return -EIO;
1413

1414
        if (endswith(s, "\n"))
789✔
1415
                return 0;
1416

1417
        if (fputc('\n', f) < 0)
636✔
UNCOV
1418
                return -EIO;
×
1419

1420
        return 1;
1421
}
1422

1423
/* A bitmask of the EOL markers we know */
1424
typedef enum EndOfLineMarker {
1425
        EOL_NONE     = 0,
1426
        EOL_ZERO     = 1 << 0,  /* \0 (aka NUL) */
1427
        EOL_TEN      = 1 << 1,  /* \n (aka NL, aka LF)  */
1428
        EOL_THIRTEEN = 1 << 2,  /* \r (aka CR)  */
1429
} EndOfLineMarker;
1430

1431
static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) {
200,613,901✔
1432

1433
        if (!FLAGS_SET(flags, READ_LINE_ONLY_NUL)) {
200,613,901✔
1434
                if (c == '\n')
199,816,545✔
1435
                        return EOL_TEN;
1436
                if (c == '\r')
193,227,580✔
1437
                        return EOL_THIRTEEN;
1438
        }
1439

1440
        if (c == '\0')
194,024,920✔
1441
                return EOL_ZERO;
24,996✔
1442

1443
        return EOL_NONE;
1444
}
1445

1446
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile, NULL);
6,173,386✔
1447

1448
int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) {
6,173,386✔
1449
        _cleanup_free_ char *buffer = NULL;
6,173,386✔
1450
        size_t n = 0, count = 0;
6,173,386✔
1451
        int r;
6,173,386✔
1452

1453
        assert(f);
6,173,386✔
1454

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

1479
        if (ret) {
6,173,386✔
1480
                if (!GREEDY_REALLOC(buffer, 1))
6,173,355✔
1481
                        return -ENOMEM;
1482
        }
1483

1484
        {
1485
                _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
6,173,386✔
1486
                EndOfLineMarker previous_eol = EOL_NONE;
6,173,386✔
1487
                flockfile(f);
6,173,386✔
1488

1489
                for (;;) {
201,057,802✔
1490
                        EndOfLineMarker eol;
201,057,802✔
1491
                        char c;
201,057,802✔
1492

1493
                        if (n >= limit)
201,057,802✔
1494
                                return -ENOBUFS;
22✔
1495

1496
                        if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */
201,057,796✔
1497
                                return -ENOBUFS;
1498

1499
                        r = safe_fgetc(f, &c);
201,057,796✔
1500
                        if (r < 0)
201,057,796✔
1501
                                return r;
1502
                        if (r == 0) /* EOF is definitely EOL */
201,057,780✔
1503
                                break;
1504

1505
                        eol = categorize_eol(c, flags);
200,613,901✔
1506

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

1523
                        count++;
194,884,416✔
1524

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

1532
                                if ((flags & (READ_LINE_IS_A_TTY|READ_LINE_NOT_A_TTY)) == 0) {
6,043,980✔
1533
                                        int fd;
5,310,158✔
1534

1535
                                        fd = fileno(f);
5,310,158✔
1536
                                        if (fd < 0) /* Maybe an fmemopen() stream? Handle this gracefully,
5,310,158✔
1537
                                                     * and don't call isatty() on an invalid fd */
1538
                                                flags |= READ_LINE_NOT_A_TTY;
28✔
1539
                                        else
1540
                                                flags |= isatty_safe(fd) ? READ_LINE_IS_A_TTY : READ_LINE_NOT_A_TTY;
10,620,260✔
1541
                                }
1542
                                if (FLAGS_SET(flags, READ_LINE_IS_A_TTY))
6,043,980✔
1543
                                        break;
1544
                        }
1545

1546
                        if (eol != EOL_NONE) {
194,884,416✔
1547
                                previous_eol |= eol;
6,043,980✔
1548
                                continue;
6,043,980✔
1549
                        }
1550

1551
                        if (ret) {
188,840,436✔
1552
                                if (!GREEDY_REALLOC(buffer, n + 2))
188,840,336✔
1553
                                        return -ENOMEM;
1554

1555
                                buffer[n] = c;
188,840,336✔
1556
                        }
1557

1558
                        n++;
188,840,436✔
1559
                }
1560
        }
1561

1562
        if (ret) {
6,173,364✔
1563
                buffer[n] = 0;
6,173,333✔
1564

1565
                *ret = TAKE_PTR(buffer);
6,173,333✔
1566
        }
1567

1568
        return (int) count;
6,173,364✔
1569
}
1570

1571
int read_stripped_line(FILE *f, size_t limit, char **ret) {
2,587,159✔
1572
        _cleanup_free_ char *s = NULL;
2,587,159✔
1573
        int r, k;
2,587,159✔
1574

1575
        assert(f);
2,587,159✔
1576

1577
        r = read_line(f, limit, ret ? &s : NULL);
2,587,159✔
1578
        if (r < 0)
2,587,159✔
1579
                return r;
1580

1581
        if (ret) {
2,587,159✔
1582
                const char *p = strstrip(s);
2,587,159✔
1583
                if (p == s)
2,587,159✔
1584
                        *ret = TAKE_PTR(s);
2,587,156✔
1585
                else {
1586
                        k = strdup_to(ret, p);
3✔
1587
                        if (k < 0)
3✔
1588
                                return k;
1589
                }
1590
        }
1591

1592
        return r > 0;          /* Return 1 if something was read. */
2,587,159✔
1593
}
1594

1595
int safe_fgetc(FILE *f, char *ret) {
201,064,892✔
1596
        int k;
201,064,892✔
1597

1598
        assert(f);
201,064,892✔
1599

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

1604
        errno = 0;
201,064,892✔
1605
        k = fgetc(f);
201,064,892✔
1606
        if (k == EOF) {
201,064,892✔
1607
                if (ferror(f))
443,995✔
1608
                        return errno_or_else(EIO);
32✔
1609

1610
                if (ret)
443,979✔
1611
                        *ret = 0;
443,897✔
1612

1613
                return 0;
443,979✔
1614
        }
1615

1616
        if (ret)
200,620,897✔
1617
                *ret = k;
200,620,897✔
1618

1619
        return 1;
1620
}
1621

1622
int warn_file_is_world_accessible(const char *filename, struct stat *st, const char *unit, unsigned line) {
149✔
1623
        struct stat _st;
149✔
1624

1625
        if (!filename)
149✔
1626
                return 0;
149✔
1627

1628
        if (!st) {
149✔
1629
                if (stat(filename, &_st) < 0)
22✔
UNCOV
1630
                        return -errno;
×
1631
                st = &_st;
1632
        }
1633

1634
        if ((st->st_mode & S_IRWXO) == 0)
149✔
1635
                return 0;
1636

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