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

systemd / systemd / 19053295430

03 Nov 2025 12:31PM UTC coverage: 72.279% (+0.06%) from 72.222%
19053295430

push

github

DaanDeMeyer
mkosi: update fedora commit reference to 8e2833a5b

* 8e2833a5b6 Automatically figure out the name of the top-level tar dir
* dffbf2beba Make sure fallback source is listed first
* 1d3b892105 Enable sysupdate and sysupdated

306030 of 423401 relevant lines covered (72.28%)

1089556.4 hits per line

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

92.83
/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) {
339,050✔
49
        assert(ret);
339,050✔
50

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

55
        (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
339,050✔
56

57
        *ret = f;
339,050✔
58
        return 0;
339,050✔
59
}
60

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

64
        assert(fd);
339,050✔
65

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

70
        *fd = -EBADF;
339,050✔
71

72
        return 0;
339,050✔
73
}
74

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

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

82
        *fd = -EBADF;
39,773✔
83

84
        return f;
39,773✔
85
}
86

87
DIR* take_fdopendir(int *dfd) {
202,378✔
88
        assert(dfd);
202,378✔
89

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

94
        *dfd = -EBADF;
202,378✔
95

96
        return d;
202,378✔
97
}
98

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

104
        (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
761,163✔
105

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

125
        bool needs_nl;
162,756✔
126
        int r, fd = -EBADF;
162,756✔
127

128
        assert(f);
162,756✔
129
        assert(line);
162,756✔
130

131
        if (ferror(f))
162,756✔
132
                return -EIO;
133

134
        if (ts) {
162,756✔
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) {
162,756✔
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,516✔
157
                    streq_skip_trailing_chars(line, t, NEWLINE)) {
8,662✔
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");
156,259✔
167

168
        if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) {
48,934✔
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");
238,795✔
173
                needs_nl = false;
47,759✔
174
        }
175

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

179
        if (needs_nl)
156,251✔
180
                if (fputc('\n', f) == EOF)
1,174✔
181
                        return -errno;
×
182

183
        if (flags & WRITE_STRING_FILE_SYNC)
156,251✔
184
                r = fflush_sync_and_check(f);
1,718✔
185
        else
186
                r = fflush_and_check(f);
154,533✔
187
        if (r < 0)
156,251✔
188
                return r;
189

190
        if (ts) {
156,231✔
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,469✔
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,469✔
211
                FLAGS_SET(flags, WRITE_STRING_FILE_MODE_0444) ? 0444 : 0644;
83,235✔
212
}
213

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

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

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

239
                call_label_ops_post = true;
240
        }
241

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

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

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

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

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

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

273
        return 0;
274
}
275

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

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

295
        if (flags & WRITE_STRING_FILE_MKDIR_0755) {
143,377✔
296
                assert(fn);
242✔
297

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

303
        if (flags & WRITE_STRING_FILE_ATOMIC) {
143,377✔
304
                assert(fn);
2,545✔
305
                assert(flags & WRITE_STRING_FILE_CREATE);
2,545✔
306

307
                r = write_string_file_atomic_at(dir_fd, fn, line, flags, ts);
2,545✔
308
                if (r < 0)
2,545✔
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))
140,832✔
316
                r = fd = fd_reopen(
59,908✔
317
                                ASSERT_FD(dir_fd), O_CLOEXEC | O_NOCTTY |
59,908✔
318
                                (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
119,816✔
319
                                (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY) |
59,908✔
320
                                (FLAGS_SET(flags, WRITE_STRING_FILE_OPEN_NONBLOCKING) ? O_NONBLOCK : 0));
59,908✔
321
        else {
322
                mode_t mode = write_string_file_flags_to_mode(flags);
80,924✔
323
                bool call_label_ops_post = false;
80,924✔
324

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

330
                        call_label_ops_post = true;
331
                }
332

333
                r = fd = openat_report_new(
242,772✔
334
                                dir_fd, fn, O_CLOEXEC | O_NOCTTY |
80,924✔
335
                                (FLAGS_SET(flags, WRITE_STRING_FILE_NOFOLLOW) ? O_NOFOLLOW : 0) |
80,924✔
336
                                (FLAGS_SET(flags, WRITE_STRING_FILE_CREATE) ? O_CREAT : 0) |
80,924✔
337
                                (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
161,848✔
338
                                (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY) |
80,924✔
339
                                (FLAGS_SET(flags, WRITE_STRING_FILE_OPEN_NONBLOCKING) ? O_NONBLOCK : 0),
80,924✔
340
                                mode,
341
                                &made_file);
342
                if (call_label_ops_post)
80,924✔
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,239✔
346
        }
347
        if (r < 0)
140,832✔
348
                goto fail;
1,555✔
349

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

354
        if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
139,277✔
355
                setvbuf(f, NULL, _IONBF, 0);
138,074✔
356

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

361
        return 0;
362

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

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

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

378
        return r;
379
}
380

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

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

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

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

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

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

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

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

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

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

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

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

428
        return read_line(f, LONG_LINE_MAX, ret);
152,923✔
429
}
430

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

437
        assert(blob);
1,538✔
438

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

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

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

448
        r = fopen_unlocked_at(dir_fd, strempty(fn), "re", 0, &f);
1,538✔
449
        if (r < 0)
1,538✔
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;
866✔
454
        k = fread(buf, 1, l + accept_extra_nl + 1, f);
866✔
455
        if (ferror(f))
866✔
456
                return errno_or_else(EIO);
×
457

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

465
        return 1;
466
}
467

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

500
        _cleanup_close_ int fd = -EBADF;
737,726✔
501
        if (isempty(filename))
737,726✔
502
                fd = fd_reopen(ASSERT_FD(dir_fd), O_RDONLY | O_NOCTTY | O_CLOEXEC);
567,466✔
503
        else
504
                fd = RET_NERRNO(openat(dir_fd, filename, O_RDONLY | O_NOCTTY | O_CLOEXEC));
170,260✔
505
        if (fd < 0)
737,726✔
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 (;;) {
685,723✔
512
                struct stat st;
685,722✔
513

514
                if (fstat(fd, &st) < 0)
685,722✔
515
                        return -errno;
1,160✔
516

517
                if (!S_ISREG(st.st_mode))
685,722✔
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);
685,722✔
522
                if (st.st_size > 0 && n_retries > 1) {
685,722✔
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. */
512,556✔
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);
512,556✔
534

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

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

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

557
                for (;;) {
685,722✔
558
                        ssize_t k;
685,722✔
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);
685,722✔
564
                        if (k >= 0) {
685,722✔
565
                                n = k;
684,562✔
566
                                break;
684,562✔
567
                        }
568

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

573
                /* Consider a short read as EOF */
574
                if (n <= size)
684,562✔
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,370✔
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) {
684,561✔
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))
647,448✔
609
                        return -EBADMSG;
610

611
                if (n < size) {
647,448✔
612
                        char *p;
639,033✔
613

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

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

625
        if (ret_size)
684,561✔
626
                *ret_size = n;
526,492✔
627

628
        return !truncated;
684,561✔
629
}
630

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

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

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

652
        if ((flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) != 0) {
449,608✔
653
                if (size <= SIZE_MAX / READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY)
59✔
654
                        size *= READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY;
57✔
655
                else
656
                        size = SIZE_MAX;
657
        }
658

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

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

667
                if (FLAGS_SET(flags, READ_FULL_FILE_VERIFY_REGULAR)) {
449,500✔
668
                        r = stat_verify_regular(&st);
×
669
                        if (r < 0)
×
670
                                return r;
671
                }
672

673
                if (S_ISREG(st.st_mode)) {
449,500✔
674

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

681
                        if (st.st_size > 0 &&
449,077✔
682
                            (size == SIZE_MAX || FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER))) {
1,290✔
683

684
                                uint64_t rsize =
1,283,574✔
685
                                        LESS_BY((uint64_t) st.st_size, offset == UINT64_MAX ? 0 : offset);
427,858✔
686

687
                                if (rsize < SIZE_MAX) /* overflow check */
427,858✔
688
                                        n_next = rsize + 1;
427,858✔
689
                        }
690

691
                        if (flags & READ_FULL_FILE_WARN_WORLD_READABLE)
449,077✔
692
                                (void) warn_file_is_world_accessible(filename, &st, NULL, 0);
127✔
693
                }
694
        } else if (FLAGS_SET(flags, READ_FULL_FILE_VERIFY_REGULAR))
108✔
695
                return -EBADFD;
696

697
        /* If we don't know how much to read, figure it out now. If we shall read a part of the file, then
698
         * allocate the requested size. If we shall load the full file start with LINE_MAX. Note that if
699
         * READ_FULL_FILE_FAIL_WHEN_LARGER we consider the specified size a safety limit, and thus also start
700
         * with LINE_MAX, under assumption the file is most likely much shorter. */
701
        if (n_next == 0)
449,500✔
702
                n_next = size != SIZE_MAX && !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) ? size : LINE_MAX;
21,750✔
703

704
        /* Never read more than we need to determine that our own limit is hit */
705
        if (n_next > READ_FULL_BYTES_MAX)
428,052✔
706
                n_next = READ_FULL_BYTES_MAX + 1;
×
707

708
        if (offset != UINT64_MAX && fseek(f, offset, SEEK_SET) < 0)
449,608✔
709
                return -errno;
×
710

711
        n = l = 0;
712
        for (;;) {
449,980✔
713
                char *t;
449,794✔
714
                size_t k;
449,794✔
715

716
                /* If we shall fail when reading overly large data, then read exactly one byte more than the
717
                 * specified size at max, since that'll tell us if there's anymore data beyond the limit. */
718
                if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && n_next > size)
449,794✔
719
                        n_next = size + 1;
8✔
720

721
                if (flags & READ_FULL_FILE_SECURE) {
449,794✔
722
                        t = malloc(n_next + 1);
1,515✔
723
                        if (!t) {
1,515✔
724
                                r = -ENOMEM;
×
725
                                goto finalize;
×
726
                        }
727
                        memcpy_safe(t, buf, n);
1,515✔
728
                        explicit_bzero_safe(buf, n);
1,515✔
729
                        free(buf);
1,515✔
730
                } else {
731
                        t = realloc(buf, n_next + 1);
448,279✔
732
                        if (!t)
448,279✔
733
                                return -ENOMEM;
734
                }
735

736
                buf = t;
449,794✔
737
                /* Unless a size has been explicitly specified, try to read as much as fits into the memory
738
                 * we allocated (minus 1, to leave one byte for the safety NUL byte) */
739
                n = size == SIZE_MAX ? MALLOC_SIZEOF_SAFE(buf) - 1 : n_next;
449,794✔
740

741
                errno = 0;
449,794✔
742
                k = fread(buf + l, 1, n - l, f);
449,794✔
743

744
                assert(k <= n - l);
449,794✔
745
                l += k;
449,794✔
746

747
                if (ferror(f)) {
449,794✔
748
                        r = errno_or_else(EIO);
2✔
749
                        goto finalize;
2✔
750
                }
751
                if (feof(f))
449,792✔
752
                        break;
753

754
                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✔
755
                        assert(l == size);
91✔
756
                        break;
757
                }
758

759
                assert(k > 0); /* we can't have read zero bytes because that would have been EOF */
192✔
760

761
                if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && l > size) {
192✔
762
                        r = -E2BIG;
6✔
763
                        goto finalize;
6✔
764
                }
765

766
                if (n >= READ_FULL_BYTES_MAX) {
186✔
767
                        r = -E2BIG;
×
768
                        goto finalize;
×
769
                }
770

771
                n_next = MIN(n * 2, READ_FULL_BYTES_MAX);
186✔
772
        }
773

774
        if (flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) {
449,600✔
775
                _cleanup_free_ void *decoded = NULL;
57✔
776
                size_t decoded_size;
57✔
777

778
                buf[l++] = 0;
57✔
779
                if (flags & READ_FULL_FILE_UNBASE64)
57✔
780
                        r = unbase64mem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size);
55✔
781
                else
782
                        r = unhexmem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size);
2✔
783
                if (r < 0)
57✔
784
                        goto finalize;
×
785

786
                if (flags & READ_FULL_FILE_SECURE)
57✔
787
                        explicit_bzero_safe(buf, n);
14✔
788
                free_and_replace(buf, decoded);
57✔
789
                n = l = decoded_size;
57✔
790

791
                if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && l > expected_decoded_size) {
57✔
792
                        r = -E2BIG;
×
793
                        goto finalize;
×
794
                }
795
        }
796

797
        if (!ret_size) {
449,600✔
798
                /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
799
                 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
800
                 * there'd be ambiguity about what we just read. */
801

802
                if (memchr(buf, 0, l)) {
322,723✔
803
                        r = -EBADMSG;
2✔
804
                        goto finalize;
2✔
805
                }
806
        }
807

808
        buf[l] = 0;
449,598✔
809
        *ret_contents = TAKE_PTR(buf);
449,598✔
810

811
        if (ret_size)
449,598✔
812
                *ret_size = l;
126,877✔
813

814
        return 0;
815

816
finalize:
10✔
817
        if (flags & READ_FULL_FILE_SECURE)
10✔
818
                explicit_bzero_safe(buf, n);
3✔
819

820
        return r;
821
}
822

823
int read_full_file_full(
626,803✔
824
                int dir_fd,
825
                const char *filename,
826
                uint64_t offset,
827
                size_t size,
828
                ReadFullFileFlags flags,
829
                const char *bind_name,
830
                char **ret_contents,
831
                size_t *ret_size) {
832

833
        _cleanup_fclose_ FILE *f = NULL;
626,803✔
834
        XfopenFlags xflags = XFOPEN_UNLOCKED;
626,803✔
835
        int r;
626,803✔
836

837
        assert(ret_contents);
626,803✔
838

839
        if (FLAGS_SET(flags, READ_FULL_FILE_CONNECT_SOCKET) && /* If this is enabled, let's try to connect to it */
626,803✔
840
            offset == UINT64_MAX)                              /* Seeking is not supported on AF_UNIX sockets */
841
                xflags |= XFOPEN_SOCKET;
192✔
842

843
        r = xfopenat_full(dir_fd, filename, "re", 0, xflags, bind_name, &f);
626,803✔
844
        if (r < 0)
626,803✔
845
                return r;
846

847
        return read_full_stream_full(f, filename, offset, size, flags, ret_contents, ret_size);
433,930✔
848
}
849

850
int script_get_shebang_interpreter(const char *path, char **ret) {
8✔
851
        _cleanup_fclose_ FILE *f = NULL;
8✔
852
        int r;
8✔
853

854
        assert(path);
8✔
855

856
        f = fopen(path, "re");
8✔
857
        if (!f)
8✔
858
                return -errno;
1✔
859

860
        char c;
7✔
861
        r = safe_fgetc(f, &c);
7✔
862
        if (r < 0)
7✔
863
                return r;
864
        if (r == 0)
7✔
865
                return -EBADMSG;
866
        if (c != '#')
7✔
867
                return -EMEDIUMTYPE;
868
        r = safe_fgetc(f, &c);
2✔
869
        if (r < 0)
2✔
870
                return r;
871
        if (r == 0)
2✔
872
                return -EBADMSG;
873
        if (c != '!')
2✔
874
                return -EMEDIUMTYPE;
875

876
        _cleanup_free_ char *line = NULL;
2✔
877
        r = read_line(f, LONG_LINE_MAX, &line);
2✔
878
        if (r < 0)
2✔
879
                return r;
880

881
        _cleanup_free_ char *p = NULL;
2✔
882
        const char *s = line;
2✔
883

884
        r = extract_first_word(&s, &p, /* separators = */ NULL, /* flags = */ 0);
2✔
885
        if (r < 0)
2✔
886
                return r;
887
        if (r == 0)
2✔
888
                return -ENOEXEC;
889

890
        if (ret)
2✔
891
                *ret = TAKE_PTR(p);
2✔
892
        return 0;
893
}
894

895
int get_proc_field(const char *path, const char *key, char **ret) {
51,202✔
896
        _cleanup_fclose_ FILE *f = NULL;
51,202✔
897
        int r;
51,202✔
898

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

904
        assert(path);
51,202✔
905
        assert(key);
51,202✔
906

907
        r = fopen_unlocked(path, "re", &f);
51,202✔
908
        if (r == -ENOENT && proc_mounted() == 0)
51,202✔
909
                return -ENOSYS;
910
        if (r < 0)
51,187✔
911
                return r;
912

913
        for (;;) {
323,601✔
914
                 _cleanup_free_ char *line = NULL;
183,836✔
915

916
                 r = read_line(f, LONG_LINE_MAX, &line);
183,836✔
917
                 if (r < 0)
183,836✔
918
                         return r;
919
                 if (r == 0)
183,836✔
920
                         return -ENODATA;
921

922
                 char *l = startswith(line, key);
183,836✔
923
                 if (l && *l == ':') {
183,836✔
924
                         if (ret) {
44,071✔
925
                                 char *s = strdupcspn(skip_leading_chars(l + 1, " \t"), WHITESPACE);
44,071✔
926
                                 if (!s)
44,071✔
927
                                         return -ENOMEM;
928

929
                                 *ret = s;
44,071✔
930
                         }
931

932
                         return 0;
44,071✔
933
                 }
934
        }
935
}
936

937
DIR* xopendirat(int dir_fd, const char *path, int flags) {
166,071✔
938
        _cleanup_close_ int fd = -EBADF;
166,071✔
939

940
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
166,071✔
941
        assert(!(flags & (O_CREAT|O_TMPFILE)));
166,071✔
942

943
        if ((dir_fd == AT_FDCWD || path_is_absolute(path)) &&
166,440✔
944
            (flags &~ O_DIRECTORY) == 0)
1,384✔
945
                return opendir(path);
×
946

947
        if (isempty(path)) {
166,071✔
948
                path = ".";
164,318✔
949
                flags |= O_NOFOLLOW;
164,318✔
950
        }
951

952
        fd = openat(dir_fd, path, O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
166,071✔
953
        if (fd < 0)
166,071✔
954
                return NULL;
955

956
        return take_fdopendir(&fd);
165,576✔
957
}
958

959
int fopen_mode_to_flags(const char *mode) {
74,760✔
960
        const char *p;
74,760✔
961
        int flags;
74,760✔
962

963
        assert(mode);
74,760✔
964

965
        if ((p = startswith(mode, "r+")))
74,760✔
966
                flags = O_RDWR;
967
        else if ((p = startswith(mode, "r")))
74,759✔
968
                flags = O_RDONLY;
969
        else if ((p = startswith(mode, "w+")))
×
970
                flags = O_RDWR|O_CREAT|O_TRUNC;
971
        else if ((p = startswith(mode, "w")))
×
972
                flags = O_WRONLY|O_CREAT|O_TRUNC;
973
        else if ((p = startswith(mode, "a+")))
×
974
                flags = O_RDWR|O_CREAT|O_APPEND;
975
        else if ((p = startswith(mode, "a")))
×
976
                flags = O_WRONLY|O_CREAT|O_APPEND;
977
        else
978
                return -EINVAL;
979

980
        for (; *p != 0; p++) {
145,934✔
981

982
                switch (*p) {
71,174✔
983

984
                case 'e':
71,174✔
985
                        flags |= O_CLOEXEC;
71,174✔
986
                        break;
71,174✔
987

988
                case 'x':
×
989
                        flags |= O_EXCL;
×
990
                        break;
×
991

992
                case 'm':
993
                        /* ignore this here, fdopen() might care later though */
994
                        break;
995

996
                case 'c': /* not sure what to do about this one */
997
                default:
998
                        return -EINVAL;
999
                }
1000
        }
1001

1002
        return flags;
1003
}
1004

1005
static int xfopenat_regular(int dir_fd, const char *path, const char *mode, int open_flags, FILE **ret) {
879,572✔
1006
        FILE *f;
879,572✔
1007

1008
        /* A combination of fopen() with openat() */
1009

1010
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
879,572✔
1011
        assert(mode);
879,572✔
1012
        assert(ret);
879,572✔
1013

1014
        if (dir_fd == AT_FDCWD && open_flags == 0 && path)
879,572✔
1015
                f = fopen(path, mode);
878,571✔
1016
        else {
1017
                _cleanup_close_ int fd = -EBADF;
1,001✔
1018
                int mode_flags;
1,001✔
1019

1020
                mode_flags = fopen_mode_to_flags(mode);
1,001✔
1021
                if (mode_flags < 0)
1,001✔
1022
                        return mode_flags;
1023

1024
                if (path) {
1,001✔
1025
                        fd = openat(dir_fd, path, mode_flags | open_flags);
989✔
1026
                        if (fd < 0)
989✔
1027
                                return -errno;
394✔
1028
                } else {
1029
                        if (dir_fd == AT_FDCWD)
12✔
1030
                                return -EBADF;
1031

1032
                        fd = fd_reopen(dir_fd, mode_flags | open_flags);
12✔
1033
                        if (fd < 0)
12✔
1034
                                return fd;
1035
                }
1036

1037
                f = take_fdopen(&fd, mode);
607✔
1038
        }
1039
        if (!f)
879,178✔
1040
                return -errno;
226,875✔
1041

1042
        *ret = f;
652,303✔
1043
        return 0;
652,303✔
1044
}
1045

1046
static int xfopenat_unix_socket(int dir_fd, const char *path, const char *bind_name, FILE **ret) {
1✔
1047
        _cleanup_close_ int sk = -EBADF;
1✔
1048
        FILE *f;
1✔
1049
        int r;
1✔
1050

1051
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1✔
1052
        assert(ret);
1✔
1053

1054
        sk = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
1✔
1055
        if (sk < 0)
1✔
1056
                return -errno;
×
1057

1058
        if (bind_name) {
1✔
1059
                /* If the caller specified a socket name to bind to, do so before connecting. This is
1060
                 * useful to communicate some minor, short meta-information token from the client to
1061
                 * the server. */
1062
                union sockaddr_union bsa;
1✔
1063

1064
                r = sockaddr_un_set_path(&bsa.un, bind_name);
1✔
1065
                if (r < 0)
1✔
1066
                        return r;
×
1067

1068
                if (bind(sk, &bsa.sa, r) < 0)
1✔
1069
                        return -errno;
×
1070
        }
1071

1072
        r = connect_unix_path(sk, dir_fd, path);
1✔
1073
        if (r < 0)
1✔
1074
                return r;
1075

1076
        if (shutdown(sk, SHUT_WR) < 0)
1✔
1077
                return -errno;
×
1078

1079
        f = take_fdopen(&sk, "r");
1✔
1080
        if (!f)
1✔
1081
                return -errno;
×
1082

1083
        *ret = f;
1✔
1084
        return 0;
1✔
1085
}
1086

1087
int xfopenat_full(
879,572✔
1088
                int dir_fd,
1089
                const char *path,
1090
                const char *mode,
1091
                int open_flags,
1092
                XfopenFlags flags,
1093
                const char *bind_name,
1094
                FILE **ret) {
1095

1096
        FILE *f = NULL;  /* avoid false maybe-uninitialized warning */
879,572✔
1097
        int r;
879,572✔
1098

1099
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
879,572✔
1100
        assert(mode);
879,572✔
1101
        assert(ret);
879,572✔
1102

1103
        r = xfopenat_regular(dir_fd, path, mode, open_flags, &f);
879,572✔
1104
        if (r == -ENXIO && FLAGS_SET(flags, XFOPEN_SOCKET)) {
879,572✔
1105
                /* ENXIO is what Linux returns if we open a node that is an AF_UNIX socket */
1106
                r = xfopenat_unix_socket(dir_fd, path, bind_name, &f);
1✔
1107
                if (IN_SET(r, -ENOTSOCK, -EINVAL))
1✔
1108
                        return -ENXIO; /* propagate original error if this is not a socket after all */
879,572✔
1109
        }
1110
        if (r < 0)
879,572✔
1111
                return r;
1112

1113
        if (FLAGS_SET(flags, XFOPEN_UNLOCKED))
652,304✔
1114
                (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
652,064✔
1115

1116
        *ret = f;
652,304✔
1117
        return 0;
652,304✔
1118
}
1119

1120
int fdopen_independent(int fd, const char *mode, FILE **ret) {
11,316✔
1121
        _cleanup_close_ int copy_fd = -EBADF;
11,316✔
1122
        _cleanup_fclose_ FILE *f = NULL;
11,316✔
1123
        int mode_flags;
11,316✔
1124

1125
        assert(fd >= 0);
11,316✔
1126
        assert(mode);
11,316✔
1127
        assert(ret);
11,316✔
1128

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

1132
        mode_flags = fopen_mode_to_flags(mode);
11,316✔
1133
        if (mode_flags < 0)
11,316✔
1134
                return mode_flags;
1135

1136
        /* Flags returned by fopen_mode_to_flags might contain O_CREAT, but it doesn't make sense for fd_reopen
1137
         * since we're working on an existing fd anyway. Let's drop it here to avoid triggering assertion. */
1138
        copy_fd = fd_reopen(fd, mode_flags & ~O_CREAT);
11,316✔
1139
        if (copy_fd < 0)
11,316✔
1140
                return copy_fd;
1141

1142
        f = take_fdopen(&copy_fd, mode);
11,316✔
1143
        if (!f)
11,316✔
1144
                return -errno;
×
1145

1146
        *ret = TAKE_PTR(f);
11,316✔
1147
        return 0;
11,316✔
1148
}
1149

1150
static int search_and_open_internal(
24,198✔
1151
                const char *path,
1152
                int mode,            /* if ret_fd is NULL this is an [FRWX]_OK mode for access(), otherwise an open mode for open() */
1153
                const char *root,
1154
                char **search,
1155
                int *ret_fd,
1156
                char **ret_path) {
1157

1158
        int r;
24,198✔
1159

1160
        assert(!ret_fd || !FLAGS_SET(mode, O_CREAT)); /* We don't support O_CREAT for this */
24,198✔
1161
        assert(path);
24,198✔
1162

1163
        if (path_is_absolute(path)) {
24,198✔
1164
                _cleanup_close_ int fd = -EBADF;
×
1165

1166
                if (ret_fd)
85✔
1167
                        /* We only specify 0777 here to appease static analyzers, it's never used since we
1168
                         * don't support O_CREAT here */
1169
                        r = fd = RET_NERRNO(open(path, mode, 0777));
83✔
1170
                else
1171
                        r = RET_NERRNO(access(path, mode));
2✔
1172
                if (r < 0)
4✔
1173
                        return r;
1174

1175
                if (ret_path) {
81✔
1176
                        r = path_simplify_alloc(path, ret_path);
81✔
1177
                        if (r < 0)
81✔
1178
                                return r;
1179
                }
1180

1181
                if (ret_fd)
81✔
1182
                        *ret_fd = TAKE_FD(fd);
80✔
1183

1184
                return 0;
81✔
1185
        }
1186

1187
        if (!path_strv_resolve_uniq(search, root))
24,113✔
1188
                return -ENOMEM;
1189

1190
        STRV_FOREACH(i, search) {
133,411✔
1191
                _cleanup_close_ int fd = -EBADF;
133,496✔
1192
                _cleanup_free_ char *p = NULL;
111,489✔
1193

1194
                p = path_join(root, *i, path);
111,489✔
1195
                if (!p)
111,489✔
1196
                        return -ENOMEM;
1197

1198
                if (ret_fd)
111,489✔
1199
                        /* as above, 0777 is static analyzer appeasement */
1200
                        r = fd = RET_NERRNO(open(p, mode, 0777));
111,125✔
1201
                else
1202
                        r = RET_NERRNO(access(p, F_OK));
364✔
1203
                if (r >= 0) {
109,298✔
1204
                        if (ret_path)
2,191✔
1205
                                *ret_path = path_simplify(TAKE_PTR(p));
2,191✔
1206

1207
                        if (ret_fd)
2,191✔
1208
                                *ret_fd = TAKE_FD(fd);
2,184✔
1209

1210
                        return 0;
2,191✔
1211
                }
1212
                if (r != -ENOENT)
109,298✔
1213
                        return r;
1214
        }
1215

1216
        return -ENOENT;
1217
}
1218

1219
int search_and_open(
24,198✔
1220
                const char *path,
1221
                int mode,
1222
                const char *root,
1223
                char **search,
1224
                int *ret_fd,
1225
                char **ret_path) {
1226

1227
        _cleanup_strv_free_ char **copy = NULL;
24,198✔
1228

1229
        assert(path);
24,198✔
1230

1231
        copy = strv_copy((char**) search);
24,198✔
1232
        if (!copy)
24,198✔
1233
                return -ENOMEM;
1234

1235
        return search_and_open_internal(path, mode, root, copy, ret_fd, ret_path);
24,198✔
1236
}
1237

1238
static int search_and_fopen_internal(
24,193✔
1239
                const char *path,
1240
                const char *mode,
1241
                const char *root,
1242
                char **search,
1243
                FILE **ret_file,
1244
                char **ret_path) {
1245

1246
        _cleanup_free_ char *found_path = NULL;
24,193✔
1247
        _cleanup_close_ int fd = -EBADF;
24,193✔
1248
        int r;
24,193✔
1249

1250
        assert(path);
24,193✔
1251
        assert(mode || !ret_file);
24,193✔
1252

1253
        r = search_and_open(
48,492✔
1254
                        path,
1255
                        mode ? fopen_mode_to_flags(mode) : 0,
24,019✔
1256
                        root,
1257
                        search,
1258
                        ret_file ? &fd : NULL,
1259
                        ret_path ? &found_path : NULL);
1260
        if (r < 0)
24,193✔
1261
                return r;
1262

1263
        if (ret_file) {
2,267✔
1264
                FILE *f = take_fdopen(&fd, mode);
2,264✔
1265
                if (!f)
2,264✔
1266
                        return -errno;
×
1267

1268
                *ret_file = f;
2,264✔
1269
        }
1270

1271
        if (ret_path)
2,267✔
1272
                *ret_path = TAKE_PTR(found_path);
2,267✔
1273

1274
        return 0;
1275
}
1276

1277
int search_and_fopen(
86✔
1278
                const char *path,
1279
                const char *mode,
1280
                const char *root,
1281
                const char **search,
1282
                FILE **ret_file,
1283
                char **ret_path) {
1284

1285
        _cleanup_strv_free_ char **copy = NULL;
86✔
1286

1287
        assert(path);
86✔
1288
        assert(mode || !ret_file);
86✔
1289

1290
        copy = strv_copy((char**) search);
86✔
1291
        if (!copy)
86✔
1292
                return -ENOMEM;
1293

1294
        return search_and_fopen_internal(path, mode, root, copy, ret_file, ret_path);
86✔
1295
}
1296

1297
int search_and_fopen_nulstr(
24,107✔
1298
                const char *path,
1299
                const char *mode,
1300
                const char *root,
1301
                const char *search,
1302
                FILE **ret_file,
1303
                char **ret_path) {
1304

1305
        _cleanup_strv_free_ char **l = NULL;
24,107✔
1306

1307
        assert(path);
24,107✔
1308
        assert(mode || !ret_file);
24,107✔
1309

1310
        l = strv_split_nulstr(search);
24,107✔
1311
        if (!l)
24,107✔
1312
                return -ENOMEM;
1313

1314
        return search_and_fopen_internal(path, mode, root, l, ret_file, ret_path);
24,107✔
1315
}
1316

1317
int fflush_and_check(FILE *f) {
1,081,931✔
1318
        assert(f);
1,081,931✔
1319

1320
        errno = 0;
1,081,931✔
1321
        fflush(f);
1,081,931✔
1322

1323
        if (ferror(f))
1,081,931✔
1324
                return errno_or_else(EIO);
44✔
1325

1326
        return 0;
1327
}
1328

1329
int fflush_sync_and_check(FILE *f) {
2,153✔
1330
        int r, fd;
2,153✔
1331

1332
        assert(f);
2,153✔
1333

1334
        r = fflush_and_check(f);
2,153✔
1335
        if (r < 0)
2,153✔
1336
                return r;
1337

1338
        /* Not all file streams have an fd associated (think: fmemopen()), let's handle this gracefully and
1339
         * assume that in that case we need no explicit syncing */
1340
        fd = fileno(f);
2,153✔
1341
        if (fd < 0)
2,153✔
1342
                return 0;
1343

1344
        r = fsync_full(fd);
2,153✔
1345
        if (r < 0)
2,153✔
1346
                return r;
×
1347

1348
        return 0;
1349
}
1350

1351
int write_timestamp_file_atomic(const char *fn, usec_t n) {
200✔
1352
        char ln[DECIMAL_STR_MAX(n)+2];
200✔
1353

1354
        /* Creates a "timestamp" file, that contains nothing but a
1355
         * usec_t timestamp, formatted in ASCII. */
1356

1357
        if (!timestamp_is_set(n))
200✔
1358
                return -ERANGE;
200✔
1359

1360
        xsprintf(ln, USEC_FMT "\n", n);
200✔
1361

1362
        return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
200✔
1363
}
1364

1365
int read_timestamp_file(const char *fn, usec_t *ret) {
27✔
1366
        _cleanup_free_ char *ln = NULL;
27✔
1367
        uint64_t t;
27✔
1368
        int r;
27✔
1369

1370
        r = read_one_line_file(fn, &ln);
27✔
1371
        if (r < 0)
27✔
1372
                return r;
1373

1374
        r = safe_atou64(ln, &t);
×
1375
        if (r < 0)
×
1376
                return r;
1377

1378
        if (!timestamp_is_set(t))
×
1379
                return -ERANGE;
1380

1381
        *ret = (usec_t) t;
×
1382
        return 0;
×
1383
}
1384

1385
int fputs_with_separator(FILE *f, const char *s, const char *separator, bool *space) {
3,454✔
1386
        assert(s);
3,454✔
1387
        assert(space);
3,454✔
1388

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

1394
        if (!f)
3,454✔
1395
                f = stdout;
×
1396

1397
        if (!separator)
3,454✔
1398
                separator = " ";
1,754✔
1399

1400
        if (*space)
3,454✔
1401
                if (fputs(separator, f) < 0)
1,534✔
1402
                        return -EIO;
1403

1404
        *space = true;
3,454✔
1405

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

1409
        return 0;
1410
}
1411

1412
int fputs_with_newline(FILE *f, const char *s) {
827✔
1413

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

1417
        if (isempty(s))
827✔
1418
                return 0;
1419

1420
        if (!f)
827✔
1421
                f = stdout;
×
1422

1423
        if (fputs(s, f) < 0)
827✔
1424
                return -EIO;
1425

1426
        if (endswith(s, "\n"))
827✔
1427
                return 0;
1428

1429
        if (fputc('\n', f) < 0)
668✔
1430
                return -EIO;
×
1431

1432
        return 1;
1433
}
1434

1435
/* A bitmask of the EOL markers we know */
1436
typedef enum EndOfLineMarker {
1437
        EOL_NONE     = 0,
1438
        EOL_ZERO     = 1 << 0,  /* \0 (aka NUL) */
1439
        EOL_TEN      = 1 << 1,  /* \n (aka NL, aka LF)  */
1440
        EOL_THIRTEEN = 1 << 2,  /* \r (aka CR)  */
1441
} EndOfLineMarker;
1442

1443
static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) {
202,323,912✔
1444

1445
        if (!FLAGS_SET(flags, READ_LINE_ONLY_NUL)) {
202,323,912✔
1446
                if (c == '\n')
201,520,173✔
1447
                        return EOL_TEN;
1448
                if (c == '\r')
194,887,544✔
1449
                        return EOL_THIRTEEN;
1450
        }
1451

1452
        if (c == '\0')
195,691,267✔
1453
                return EOL_ZERO;
25,174✔
1454

1455
        return EOL_NONE;
1456
}
1457

1458
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile, NULL);
6,213,638✔
1459

1460
int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) {
6,213,638✔
1461
        _cleanup_free_ char *buffer = NULL;
6,213,638✔
1462
        size_t n = 0, count = 0;
6,213,638✔
1463
        int r;
6,213,638✔
1464

1465
        assert(f);
6,213,638✔
1466

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

1491
        if (ret) {
6,213,638✔
1492
                if (!GREEDY_REALLOC(buffer, 1))
6,213,607✔
1493
                        return -ENOMEM;
1494
        }
1495

1496
        {
1497
                _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
6,213,638✔
1498
                EndOfLineMarker previous_eol = EOL_NONE;
6,213,638✔
1499
                flockfile(f);
6,213,638✔
1500

1501
                for (;;) {
202,767,068✔
1502
                        EndOfLineMarker eol;
202,767,068✔
1503
                        char c;
202,767,068✔
1504

1505
                        if (n >= limit)
202,767,068✔
1506
                                return -ENOBUFS;
15✔
1507

1508
                        if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */
202,767,062✔
1509
                                return -ENOBUFS;
1510

1511
                        r = safe_fgetc(f, &c);
202,767,062✔
1512
                        if (r < 0)
202,767,062✔
1513
                                return r;
1514
                        if (r == 0) /* EOF is definitely EOL */
202,767,053✔
1515
                                break;
1516

1517
                        eol = categorize_eol(c, flags);
202,323,912✔
1518

1519
                        if (FLAGS_SET(previous_eol, EOL_ZERO) ||
202,323,912✔
1520
                            (eol == EOL_NONE && previous_eol != EOL_NONE) ||
202,301,930✔
1521
                            (eol != EOL_NONE && (previous_eol & eol) != 0)) {
6,657,813✔
1522
                                /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
1523
                                 * EOL marker has been seen right before?  In either of these three cases we are
1524
                                 * done. But first, let's put this character back in the queue. (Note that we have to
1525
                                 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
1526
                                 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
1527
                                 * pass a negative value here. That said, to complicate things further ungetc() is
1528
                                 * actually happy with most negative characters and implicitly casts them back to
1529
                                 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
1530
                                 * godawful API!) */
1531
                                assert_se(ungetc((unsigned char) c, f) != EOF);
5,770,482✔
1532
                                break;
1533
                        }
1534

1535
                        count++;
196,553,430✔
1536

1537
                        if (eol != EOL_NONE) {
190,471,105✔
1538
                                /* If we are on a tty, we can't shouldn't wait for more input, because that
1539
                                 * generally means waiting for the user, interactively. In the case of a TTY
1540
                                 * we expect only \n as the single EOL marker, so we are in the lucky
1541
                                 * position that there is no need to wait. We check this condition last, to
1542
                                 * avoid isatty() check if not necessary. */
1543

1544
                                if ((flags & (READ_LINE_IS_A_TTY|READ_LINE_NOT_A_TTY)) == 0) {
6,082,325✔
1545
                                        int fd;
5,348,429✔
1546

1547
                                        fd = fileno(f);
5,348,429✔
1548
                                        if (fd < 0) /* Maybe an fmemopen() stream? Handle this gracefully,
5,348,429✔
1549
                                                     * and don't call isatty() on an invalid fd */
1550
                                                flags |= READ_LINE_NOT_A_TTY;
28✔
1551
                                        else
1552
                                                flags |= isatty_safe(fd) ? READ_LINE_IS_A_TTY : READ_LINE_NOT_A_TTY;
10,696,802✔
1553
                                }
1554
                                if (FLAGS_SET(flags, READ_LINE_IS_A_TTY))
6,082,325✔
1555
                                        break;
1556
                        }
1557

1558
                        if (eol != EOL_NONE) {
196,553,430✔
1559
                                previous_eol |= eol;
6,082,325✔
1560
                                continue;
6,082,325✔
1561
                        }
1562

1563
                        if (ret) {
190,471,105✔
1564
                                if (!GREEDY_REALLOC(buffer, n + 2))
190,471,005✔
1565
                                        return -ENOMEM;
1566

1567
                                buffer[n] = c;
190,471,005✔
1568
                        }
1569

1570
                        n++;
190,471,105✔
1571
                }
1572
        }
1573

1574
        if (ret) {
6,213,623✔
1575
                buffer[n] = 0;
6,213,592✔
1576

1577
                *ret = TAKE_PTR(buffer);
6,213,592✔
1578
        }
1579

1580
        return (int) count;
6,213,623✔
1581
}
1582

1583
int read_stripped_line(FILE *f, size_t limit, char **ret) {
2,588,951✔
1584
        _cleanup_free_ char *s = NULL;
2,588,951✔
1585
        int r, k;
2,588,951✔
1586

1587
        assert(f);
2,588,951✔
1588

1589
        r = read_line(f, limit, ret ? &s : NULL);
2,588,951✔
1590
        if (r < 0)
2,588,951✔
1591
                return r;
1592

1593
        if (ret) {
2,588,951✔
1594
                const char *p = strstrip(s);
2,588,951✔
1595
                if (p == s)
2,588,951✔
1596
                        *ret = TAKE_PTR(s);
2,588,948✔
1597
                else {
1598
                        k = strdup_to(ret, p);
3✔
1599
                        if (k < 0)
3✔
1600
                                return k;
1601
                }
1602
        }
1603

1604
        return r > 0;          /* Return 1 if something was read. */
2,588,951✔
1605
}
1606

1607
int safe_fgetc(FILE *f, char *ret) {
202,773,619✔
1608
        int k;
202,773,619✔
1609

1610
        assert(f);
202,773,619✔
1611

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

1616
        errno = 0;
202,773,619✔
1617
        k = fgetc(f);
202,773,619✔
1618
        if (k == EOF) {
202,773,619✔
1619
                if (ferror(f))
443,248✔
1620
                        return errno_or_else(EIO);
18✔
1621

1622
                if (ret)
443,239✔
1623
                        *ret = 0;
443,157✔
1624

1625
                return 0;
443,239✔
1626
        }
1627

1628
        if (ret)
202,330,371✔
1629
                *ret = k;
202,330,371✔
1630

1631
        return 1;
1632
}
1633

1634
int warn_file_is_world_accessible(const char *filename, struct stat *st, const char *unit, unsigned line) {
149✔
1635
        struct stat _st;
149✔
1636

1637
        if (!filename)
149✔
1638
                return 0;
149✔
1639

1640
        if (!st) {
149✔
1641
                if (stat(filename, &_st) < 0)
22✔
1642
                        return -errno;
×
1643
                st = &_st;
1644
        }
1645

1646
        if ((st->st_mode & S_IRWXO) == 0)
149✔
1647
                return 0;
1648

1649
        if (unit)
34✔
1650
                log_syntax(unit, LOG_WARNING, filename, line, 0,
×
1651
                           "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1652
                           filename, st->st_mode & 07777);
1653
        else
1654
                log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
34✔
1655
                            filename, st->st_mode & 07777);
1656
        return 0;
1657
}
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