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

systemd / systemd / 15720680019

17 Jun 2025 07:58PM UTC coverage: 72.087% (-0.02%) from 72.109%
15720680019

push

github

web-flow
sd-lldp: several improvements (#37845)

This makes
- sd-lldp-tx not send machine ID as chassis ID, but use application
specific machine ID,
- sd-lldp-tx emit vlan ID if it is running on a vlan interface,
- Describe() DBus method also reply LLDP configurations,
- io.systemd.Network.GetLLDPNeighbors varlink method provides vlan ID,
if received.

Closes #37613.

59 of 76 new or added lines in 3 files covered. (77.63%)

4663 existing lines in 75 files now uncovered.

300494 of 416851 relevant lines covered (72.09%)

704683.58 hits per line

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

92.54
/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) {
350,638✔
49
        assert(ret);
350,638✔
50

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

55
        (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
350,638✔
56

57
        *ret = f;
350,638✔
58
        return 0;
350,638✔
59
}
60

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

64
        assert(fd);
350,638✔
65

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

70
        *fd = -EBADF;
350,638✔
71

72
        return 0;
350,638✔
73
}
74

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

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

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

84
        return f;
44,401✔
85
}
86

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

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

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

96
        return d;
264,700✔
97
}
98

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

104
        (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
753,003✔
105

106
        return f;
753,003✔
107
}
108

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

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

116
        return f;
103✔
117
}
118

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

125
        bool needs_nl;
150,993✔
126
        int r, fd = -EBADF;
150,993✔
127

128
        assert(f);
150,993✔
129
        assert(line);
150,993✔
130

131
        if (ferror(f))
150,993✔
132
                return -EIO;
133

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

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

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

168
        if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) {
44,650✔
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");
217,875✔
173
                needs_nl = false;
43,575✔
174
        }
175

176
        if (fputs(line, f) == EOF)
144,610✔
177
                return -errno;
23✔
178

179
        if (needs_nl)
144,587✔
180
                if (fputc('\n', f) == EOF)
1,074✔
181
                        return -errno;
×
182

183
        if (flags & WRITE_STRING_FILE_SYNC)
144,587✔
184
                r = fflush_sync_and_check(f);
1,708✔
185
        else
186
                r = fflush_and_check(f);
142,879✔
187
        if (r < 0)
144,587✔
188
                return r;
189

190
        if (ts) {
144,575✔
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) {
76,508✔
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 :
76,508✔
211
                FLAGS_SET(flags, WRITE_STRING_FILE_MODE_0444) ? 0444 : 0644;
76,298✔
212
}
213

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

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

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

239
                call_label_ops_post = true;
240
        }
241

242
        r = fopen_temporary_at(dir_fd, fn, &f, &p);
2,461✔
243
        if (call_label_ops_post)
2,461✔
244
                /* If fopen_temporary_at() failed in the above, propagate the error code, and ignore failures
245
                 * in label_ops_post(). */
246
                RET_GATHER(r, label_ops_post(f ? fileno(f) : dir_fd, f ? NULL : fn, /* created= */ !!f));
314✔
247
        if (r < 0)
2,461✔
248
                goto fail;
1✔
249

250
        r = write_string_stream_full(f, line, flags, ts);
2,460✔
251
        if (r < 0)
2,460✔
252
                goto fail;
×
253

254
        r = fchmod_umask(fileno(f), mode);
2,460✔
255
        if (r < 0)
2,460✔
256
                goto fail;
×
257

258
        r = RET_NERRNO(renameat(dir_fd, p, dir_fd, fn));
2,460✔
259
        if (r < 0)
×
260
                goto fail;
×
261

262
        if (FLAGS_SET(flags, WRITE_STRING_FILE_SYNC)) {
2,460✔
263
                /* Sync the rename, too */
264
                r = fsync_directory_of_file(fileno(f));
1,708✔
265
                if (r < 0)
1,708✔
266
                        return r;
×
267
        }
268

269
        return 0;
270

271
fail:
1✔
272
        if (f)
1✔
273
                (void) unlinkat(dir_fd, p, 0);
×
274
        return r;
275
}
276

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

285
        bool made_file = false;
134,951✔
286
        _cleanup_fclose_ FILE *f = NULL;
134,951✔
287
        _cleanup_close_ int fd = -EBADF;
134,951✔
288
        int r;
134,951✔
289

290
        assert(dir_fd == AT_FDCWD || dir_fd >= 0);
134,951✔
291
        assert(line);
134,951✔
292

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

296
        if (flags & WRITE_STRING_FILE_MKDIR_0755) {
134,951✔
297
                assert(fn);
230✔
298

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

304
        if (flags & WRITE_STRING_FILE_ATOMIC) {
134,951✔
305
                assert(fn);
2,461✔
306
                assert(flags & WRITE_STRING_FILE_CREATE);
2,461✔
307

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

312
                return r;
313
        }
314

315
        /* We manually build our own version of fopen(..., "we") that works without O_CREAT and with O_NOFOLLOW if needed. */
316
        if (isempty(fn))
132,490✔
317
                r = fd = fd_reopen(
58,443✔
318
                                ASSERT_FD(dir_fd), O_CLOEXEC | O_NOCTTY |
58,443✔
319
                                (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
116,886✔
320
                                (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY) |
58,443✔
321
                                (FLAGS_SET(flags, WRITE_STRING_FILE_OPEN_NONBLOCKING) ? O_NONBLOCK : 0));
58,443✔
322
        else {
323
                mode_t mode = write_string_file_flags_to_mode(flags);
74,047✔
324
                bool call_label_ops_post = false;
74,047✔
325

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

331
                        call_label_ops_post = true;
332
                }
333

334
                r = fd = openat_report_new(
222,141✔
335
                                dir_fd, fn, O_CLOEXEC | O_NOCTTY |
74,047✔
336
                                (FLAGS_SET(flags, WRITE_STRING_FILE_NOFOLLOW) ? O_NOFOLLOW : 0) |
74,047✔
337
                                (FLAGS_SET(flags, WRITE_STRING_FILE_CREATE) ? O_CREAT : 0) |
74,047✔
338
                                (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
148,094✔
339
                                (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY) |
74,047✔
340
                                (FLAGS_SET(flags, WRITE_STRING_FILE_OPEN_NONBLOCKING) ? O_NONBLOCK : 0),
74,047✔
341
                                mode,
342
                                &made_file);
343
                if (call_label_ops_post)
74,047✔
344
                        /* If openat_report_new() failed in the above, propagate the error code, and ignore
345
                         * failures in label_ops_post(). */
346
                        RET_GATHER(r, label_ops_post(fd >= 0 ? fd : dir_fd, fd >= 0 ? NULL : fn, made_file));
1,137✔
347
        }
348
        if (r < 0)
132,490✔
349
                goto fail;
1,570✔
350

351
        r = take_fdopen_unlocked(&fd, "w", &f);
130,920✔
352
        if (r < 0)
130,920✔
UNCOV
353
                goto fail;
×
354

355
        if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
130,920✔
356
                setvbuf(f, NULL, _IONBF, 0);
129,863✔
357

358
        r = write_string_stream_full(f, line, flags, ts);
130,920✔
359
        if (r < 0)
130,920✔
360
                goto fail;
28✔
361

362
        return 0;
363

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

368
        if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
1,599✔
369
                return r;
370

371
        f = safe_fclose(f);
1,568✔
372
        fd = safe_close(fd);
1,568✔
373

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

379
        return r;
380
}
381

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

387
        _cleanup_free_ char *p = NULL;
240✔
388
        va_list ap;
240✔
389
        int r;
240✔
390

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

395
        if (r < 0)
240✔
396
                return -ENOMEM;
397

398
        return write_string_file(fn, p, flags);
240✔
399
}
400

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

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

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

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

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

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

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

429
        return read_line(f, LONG_LINE_MAX, ret);
157,152✔
430
}
431

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

438
        assert(blob);
1,568✔
439

440
        l = strlen(blob);
1,568✔
441

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

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

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

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

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

466
        return 1;
467
}
468

469
int read_virtual_file_at(
843,494✔
470
                int dir_fd,
471
                const char *filename,
472
                size_t max_size,
473
                char **ret_contents,
474
                size_t *ret_size) {
475

476
        _cleanup_free_ char *buf = NULL;
843,494✔
477
        size_t n, size;
843,494✔
478
        int n_retries;
843,494✔
479
        bool truncated = false;
843,494✔
480

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

498
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
843,494✔
499
        assert(max_size <= READ_VIRTUAL_BYTES_MAX || max_size == SIZE_MAX);
843,494✔
500

501
        _cleanup_close_ int fd = -EBADF;
843,494✔
502
        if (isempty(filename))
843,494✔
503
                fd = fd_reopen(ASSERT_FD(dir_fd), O_RDONLY | O_NOCTTY | O_CLOEXEC);
669,922✔
504
        else
505
                fd = RET_NERRNO(openat(dir_fd, filename, O_RDONLY | O_NOCTTY | O_CLOEXEC));
173,572✔
506
        if (fd < 0)
843,494✔
507
                return fd;
508

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

512
        for (;;) {
788,419✔
513
                struct stat st;
788,418✔
514

515
                if (fstat(fd, &st) < 0)
788,418✔
516
                        return -errno;
1,169✔
517

518
                if (!S_ISREG(st.st_mode))
788,418✔
519
                        return -EBADF;
520

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

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

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

532
                                size = max_size;
533
                        } else {
534
                                size = MIN((size_t) st.st_size, max_size);
611,905✔
535

536
                                if (size > READ_VIRTUAL_BYTES_MAX)
611,905✔
537
                                        return -EFBIG;
538
                        }
539

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

551
                buf = malloc(size + 1);
788,418✔
552
                if (!buf)
788,418✔
553
                        return -ENOMEM;
554

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

558
                for (;;) {
788,418✔
559
                        ssize_t k;
788,418✔
560

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

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

574
                /* Consider a short read as EOF */
575
                if (n <= size)
787,249✔
576
                        break;
577

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

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

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

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

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

604
        if (ret_contents) {
787,248✔
605

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

612
                if (n < size) {
751,218✔
613
                        char *p;
742,909✔
614

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

622
                buf[n] = 0;
751,218✔
623
                *ret_contents = TAKE_PTR(buf);
751,218✔
624
        }
625

626
        if (ret_size)
787,248✔
627
                *ret_size = n;
625,064✔
628

629
        return !truncated;
787,248✔
630
}
631

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

641
        _cleanup_free_ char *buf = NULL;
492,554✔
642
        size_t n, n_next = 0, l, expected_decoded_size = size;
492,554✔
643
        int fd, r;
492,554✔
644

645
        assert(f);
492,554✔
646
        assert(ret_contents);
492,554✔
647
        assert(!FLAGS_SET(flags, READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX));
492,554✔
648
        assert(size != SIZE_MAX || !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER));
492,554✔
649

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

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

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

665
                if (fstat(fd, &st) < 0)
492,464✔
UNCOV
666
                        return -errno;
×
667

668
                if (S_ISREG(st.st_mode)) {
492,464✔
669

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

676
                        if (st.st_size > 0 &&
492,057✔
677
                            (size == SIZE_MAX || FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER))) {
1,253✔
678

679
                                uint64_t rsize =
1,407,306✔
680
                                        LESS_BY((uint64_t) st.st_size, offset == UINT64_MAX ? 0 : offset);
469,102✔
681

682
                                if (rsize < SIZE_MAX) /* overflow check */
469,102✔
683
                                        n_next = rsize + 1;
469,102✔
684
                        }
685

686
                        if (flags & READ_FULL_FILE_WARN_WORLD_READABLE)
492,057✔
687
                                (void) warn_file_is_world_accessible(filename, &st, NULL, 0);
130✔
688
                }
689
        }
690

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

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

702
        if (offset != UINT64_MAX && fseek(f, offset, SEEK_SET) < 0)
492,554✔
UNCOV
703
                return -errno;
×
704

705
        n = l = 0;
706
        for (;;) {
492,850✔
707
                char *t;
492,702✔
708
                size_t k;
492,702✔
709

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

715
                if (flags & READ_FULL_FILE_SECURE) {
492,702✔
716
                        t = malloc(n_next + 1);
1,449✔
717
                        if (!t) {
1,449✔
UNCOV
718
                                r = -ENOMEM;
×
UNCOV
719
                                goto finalize;
×
720
                        }
721
                        memcpy_safe(t, buf, n);
1,449✔
722
                        explicit_bzero_safe(buf, n);
1,449✔
723
                        free(buf);
1,449✔
724
                } else {
725
                        t = realloc(buf, n_next + 1);
491,253✔
726
                        if (!t)
491,253✔
727
                                return -ENOMEM;
728
                }
729

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

735
                errno = 0;
492,702✔
736
                k = fread(buf + l, 1, n - l, f);
492,702✔
737

738
                assert(k <= n - l);
492,702✔
739
                l += k;
492,702✔
740

741
                if (ferror(f)) {
492,702✔
742
                        r = errno_or_else(EIO);
2✔
743
                        goto finalize;
2✔
744
                }
745
                if (feof(f))
492,700✔
746
                        break;
747

748
                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 */
247✔
749
                        assert(l == size);
93✔
750
                        break;
751
                }
752

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

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

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

765
                n_next = MIN(n * 2, READ_FULL_BYTES_MAX);
148✔
766
        }
767

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

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

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

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

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

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

802
        buf[l] = 0;
492,544✔
803
        *ret_contents = TAKE_PTR(buf);
492,544✔
804

805
        if (ret_size)
492,544✔
806
                *ret_size = l;
136,186✔
807

808
        return 0;
809

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

814
        return r;
815
}
816

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

827
        _cleanup_fclose_ FILE *f = NULL;
682,379✔
828
        XfopenFlags xflags = XFOPEN_UNLOCKED;
682,379✔
829
        int r;
682,379✔
830

831
        assert(filename);
682,379✔
832
        assert(ret_contents);
682,379✔
833

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

838
        r = xfopenat_full(dir_fd, filename, "re", 0, xflags, bind_name, &f);
682,379✔
839
        if (r < 0)
682,379✔
840
                return r;
841

842
        return read_full_stream_full(f, filename, offset, size, flags, ret_contents, ret_size);
477,390✔
843
}
844

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

849
        assert(path);
8✔
850

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

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

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

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

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

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

890
int get_proc_field(const char *path, const char *key, char **ret) {
52,805✔
891
        _cleanup_fclose_ FILE *f = NULL;
52,805✔
892
        int r;
52,805✔
893

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

899
        assert(path);
52,805✔
900
        assert(key);
52,805✔
901

902
        r = fopen_unlocked(path, "re", &f);
52,805✔
903
        if (r == -ENOENT && proc_mounted() == 0)
52,805✔
904
                return -ENOSYS;
905
        if (r < 0)
52,793✔
906
                return r;
907

908
        for (;;) {
349,107✔
909
                 _cleanup_free_ char *line = NULL;
197,216✔
910

911
                 r = read_line(f, LONG_LINE_MAX, &line);
197,216✔
912
                 if (r < 0)
197,216✔
913
                         return r;
914
                 if (r == 0)
197,216✔
915
                         return -ENODATA;
916

917
                 char *l = startswith(line, key);
197,216✔
918
                 if (l && *l == ':') {
197,216✔
919
                         if (ret) {
45,325✔
920
                                 char *s = strdupcspn(skip_leading_chars(l + 1, " \t"), WHITESPACE);
45,325✔
921
                                 if (!s)
45,325✔
922
                                         return -ENOMEM;
923

924
                                 *ret = s;
45,325✔
925
                         }
926

927
                         return 0;
45,325✔
928
                 }
929
        }
930
}
931

932
DIR* xopendirat(int dir_fd, const char *name, int flags) {
228,552✔
933
        _cleanup_close_ int fd = -EBADF;
228,552✔
934

935
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
228,552✔
936
        assert(name);
228,552✔
937
        assert(!(flags & (O_CREAT|O_TMPFILE)));
228,552✔
938

939
        if (dir_fd == AT_FDCWD && flags == 0)
228,552✔
UNCOV
940
                return opendir(name);
×
941

942
        fd = openat(dir_fd, name, O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
228,552✔
943
        if (fd < 0)
228,552✔
944
                return NULL;
945

946
        return take_fdopendir(&fd);
228,053✔
947
}
948

949
int fopen_mode_to_flags(const char *mode) {
90,233✔
950
        const char *p;
90,233✔
951
        int flags;
90,233✔
952

953
        assert(mode);
90,233✔
954

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

970
        for (; *p != 0; p++) {
176,880✔
971

972
                switch (*p) {
86,647✔
973

974
                case 'e':
86,647✔
975
                        flags |= O_CLOEXEC;
86,647✔
976
                        break;
86,647✔
977

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

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

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

992
        return flags;
993
}
994

995
static int xfopenat_regular(int dir_fd, const char *path, const char *mode, int open_flags, FILE **ret) {
941,445✔
996
        FILE *f;
941,445✔
997

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

1000
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
941,445✔
1001
        assert(path);
941,445✔
1002
        assert(mode);
941,445✔
1003
        assert(ret);
941,445✔
1004

1005
        if (dir_fd == AT_FDCWD && open_flags == 0)
941,445✔
1006
                f = fopen(path, mode);
940,523✔
1007
        else {
1008
                _cleanup_close_ int fd = -EBADF;
922✔
1009
                int mode_flags;
922✔
1010

1011
                mode_flags = fopen_mode_to_flags(mode);
922✔
1012
                if (mode_flags < 0)
922✔
1013
                        return mode_flags;
1014

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

1019
                f = take_fdopen(&fd, mode);
551✔
1020
        }
1021
        if (!f)
941,074✔
1022
                return -errno;
238,275✔
1023

1024
        *ret = f;
702,799✔
1025
        return 0;
702,799✔
1026
}
1027

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

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

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

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

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

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

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

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

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

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

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

1079
        FILE *f = NULL;  /* avoid false maybe-uninitialized warning */
941,445✔
1080
        int r;
941,445✔
1081

1082
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
941,445✔
1083
        assert(path);
941,445✔
1084
        assert(mode);
941,445✔
1085
        assert(ret);
941,445✔
1086

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

1097
        if (FLAGS_SET(flags, XFOPEN_UNLOCKED))
702,800✔
1098
                (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
702,568✔
1099

1100
        *ret = f;
702,800✔
1101
        return 0;
702,800✔
1102
}
1103

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

1109
        assert(fd >= 0);
10,978✔
1110
        assert(mode);
10,978✔
1111
        assert(ret);
10,978✔
1112

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

1116
        mode_flags = fopen_mode_to_flags(mode);
10,978✔
1117
        if (mode_flags < 0)
10,978✔
1118
                return mode_flags;
1119

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

1126
        f = take_fdopen(&copy_fd, mode);
10,978✔
1127
        if (!f)
10,978✔
UNCOV
1128
                return -errno;
×
1129

1130
        *ret = TAKE_PTR(f);
10,978✔
1131
        return 0;
10,978✔
1132
}
1133

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

1142
        int r;
30,349✔
1143

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

1147
        if (path_is_absolute(path)) {
30,349✔
UNCOV
1148
                _cleanup_close_ int fd = -EBADF;
×
1149

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

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

1165
                if (ret_fd)
5,525✔
1166
                        *ret_fd = TAKE_FD(fd);
5,524✔
1167

1168
                return 0;
5,525✔
1169
        }
1170

1171
        if (!path_strv_resolve_uniq(search, root))
24,700✔
1172
                return -ENOMEM;
1173

1174
        STRV_FOREACH(i, search) {
137,220✔
1175
                _cleanup_close_ int fd = -EBADF;
142,869✔
1176
                _cleanup_free_ char *p = NULL;
114,643✔
1177

1178
                p = path_join(root, *i, path);
114,643✔
1179
                if (!p)
114,643✔
1180
                        return -ENOMEM;
1181

1182
                if (ret_fd)
114,643✔
1183
                        /* as above, 0777 is static analyzer appeasement */
1184
                        r = fd = RET_NERRNO(open(p, mode, 0777));
114,325✔
1185
                else
1186
                        r = RET_NERRNO(access(p, F_OK));
318✔
1187
                if (r >= 0) {
112,520✔
1188
                        if (ret_path)
2,123✔
1189
                                *ret_path = path_simplify(TAKE_PTR(p));
2,123✔
1190

1191
                        if (ret_fd)
2,123✔
1192
                                *ret_fd = TAKE_FD(fd);
2,116✔
1193

1194
                        return 0;
2,123✔
1195
                }
1196
                if (r != -ENOENT)
112,520✔
1197
                        return r;
1198
        }
1199

1200
        return -ENOENT;
1201
}
1202

1203
int search_and_open(
30,349✔
1204
                const char *path,
1205
                int mode,
1206
                const char *root,
1207
                char **search,
1208
                int *ret_fd,
1209
                char **ret_path) {
1210

1211
        _cleanup_strv_free_ char **copy = NULL;
30,349✔
1212

1213
        assert(path);
30,349✔
1214

1215
        copy = strv_copy((char**) search);
30,349✔
1216
        if (!copy)
30,349✔
1217
                return -ENOMEM;
1218

1219
        return search_and_open_internal(path, mode, root, copy, ret_fd, ret_path);
30,349✔
1220
}
1221

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

1230
        _cleanup_free_ char *found_path = NULL;
30,344✔
1231
        _cleanup_close_ int fd = -EBADF;
30,344✔
1232
        int r;
30,344✔
1233

1234
        assert(path);
30,344✔
1235
        assert(mode || !ret_file);
30,344✔
1236

1237
        r = search_and_open(
60,791✔
1238
                        path,
1239
                        mode ? fopen_mode_to_flags(mode) : 0,
30,193✔
1240
                        root,
1241
                        search,
1242
                        ret_file ? &fd : NULL,
1243
                        ret_path ? &found_path : NULL);
1244
        if (r < 0)
30,344✔
1245
                return r;
1246

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

1252
                *ret_file = f;
7,640✔
1253
        }
1254

1255
        if (ret_path)
7,643✔
1256
                *ret_path = TAKE_PTR(found_path);
7,643✔
1257

1258
        return 0;
1259
}
1260

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

1269
        _cleanup_strv_free_ char **copy = NULL;
5,654✔
1270

1271
        assert(path);
5,654✔
1272
        assert(mode || !ret_file);
5,654✔
1273

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

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

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

1289
        _cleanup_strv_free_ char **l = NULL;
24,690✔
1290

1291
        assert(path);
24,690✔
1292
        assert(mode || !ret_file);
24,690✔
1293

1294
        l = strv_split_nulstr(search);
24,690✔
1295
        if (!l)
24,690✔
1296
                return -ENOMEM;
1297

1298
        return search_and_fopen_internal(path, mode, root, l, ret_file, ret_path);
24,690✔
1299
}
1300

1301
int fflush_and_check(FILE *f) {
1,070,622✔
1302
        assert(f);
1,070,622✔
1303

1304
        errno = 0;
1,070,622✔
1305
        fflush(f);
1,070,622✔
1306

1307
        if (ferror(f))
1,070,622✔
1308
                return errno_or_else(EIO);
26✔
1309

1310
        return 0;
1311
}
1312

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

1316
        assert(f);
2,143✔
1317

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

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

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

1332
        return 0;
1333
}
1334

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

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

1341
        if (!timestamp_is_set(n))
145✔
1342
                return -ERANGE;
145✔
1343

1344
        xsprintf(ln, USEC_FMT "\n", n);
145✔
1345

1346
        return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
145✔
1347
}
1348

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

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

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

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

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

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

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

1378
        if (!f)
3,368✔
UNCOV
1379
                f = stdout;
×
1380

1381
        if (!separator)
3,368✔
1382
                separator = " ";
1,679✔
1383

1384
        if (*space)
3,368✔
1385
                if (fputs(separator, f) < 0)
1,504✔
1386
                        return -EIO;
1387

1388
        *space = true;
3,368✔
1389

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

1393
        return 0;
1394
}
1395

1396
int fputs_with_newline(FILE *f, const char *s) {
788✔
1397

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

1401
        if (isempty(s))
788✔
1402
                return 0;
1403

1404
        if (!f)
788✔
UNCOV
1405
                f = stdout;
×
1406

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

1410
        if (endswith(s, "\n"))
788✔
1411
                return 0;
1412

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

1416
        return 1;
1417
}
1418

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

1427
static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) {
203,795,684✔
1428

1429
        if (!FLAGS_SET(flags, READ_LINE_ONLY_NUL)) {
203,795,684✔
1430
                if (c == '\n')
203,053,496✔
1431
                        return EOL_TEN;
1432
                if (c == '\r')
196,363,086✔
1433
                        return EOL_THIRTEEN;
1434
        }
1435

1436
        if (c == '\0')
197,105,258✔
1437
                return EOL_ZERO;
23,320✔
1438

1439
        return EOL_NONE;
1440
}
1441

1442
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile, NULL);
6,272,382✔
1443

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

1449
        assert(f);
6,272,382✔
1450

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

1475
        if (ret) {
6,272,382✔
1476
                if (!GREEDY_REALLOC(buffer, 1))
6,272,351✔
1477
                        return -ENOMEM;
1478
        }
1479

1480
        {
1481
                _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
6,272,382✔
1482
                EndOfLineMarker previous_eol = EOL_NONE;
6,272,382✔
1483
                flockfile(f);
6,272,382✔
1484

1485
                for (;;) {
204,262,415✔
1486
                        EndOfLineMarker eol;
204,262,415✔
1487
                        char c;
204,262,415✔
1488

1489
                        if (n >= limit)
204,262,415✔
1490
                                return -ENOBUFS;
28✔
1491

1492
                        if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */
204,262,409✔
1493
                                return -ENOBUFS;
1494

1495
                        r = safe_fgetc(f, &c);
204,262,409✔
1496
                        if (r < 0)
204,262,409✔
1497
                                return r;
1498
                        if (r == 0) /* EOF is definitely EOL */
204,262,387✔
1499
                                break;
1500

1501
                        eol = categorize_eol(c, flags);
203,795,684✔
1502

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

1519
                        count++;
197,990,033✔
1520

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

1528
                                if ((flags & (READ_LINE_IS_A_TTY|READ_LINE_NOT_A_TTY)) == 0) {
6,132,087✔
1529
                                        int fd;
5,410,501✔
1530

1531
                                        fd = fileno(f);
5,410,501✔
1532
                                        if (fd < 0) /* Maybe an fmemopen() stream? Handle this gracefully,
5,410,501✔
1533
                                                     * and don't call isatty() on an invalid fd */
1534
                                                flags |= READ_LINE_NOT_A_TTY;
28✔
1535
                                        else
1536
                                                flags |= isatty_safe(fd) ? READ_LINE_IS_A_TTY : READ_LINE_NOT_A_TTY;
10,820,946✔
1537
                                }
1538
                                if (FLAGS_SET(flags, READ_LINE_IS_A_TTY))
6,132,087✔
1539
                                        break;
1540
                        }
1541

1542
                        if (eol != EOL_NONE) {
197,990,033✔
1543
                                previous_eol |= eol;
6,132,087✔
1544
                                continue;
6,132,087✔
1545
                        }
1546

1547
                        if (ret) {
191,857,946✔
1548
                                if (!GREEDY_REALLOC(buffer, n + 2))
191,857,846✔
1549
                                        return -ENOMEM;
1550

1551
                                buffer[n] = c;
191,857,846✔
1552
                        }
1553

1554
                        n++;
191,857,946✔
1555
                }
1556
        }
1557

1558
        if (ret) {
6,272,354✔
1559
                buffer[n] = 0;
6,272,323✔
1560

1561
                *ret = TAKE_PTR(buffer);
6,272,323✔
1562
        }
1563

1564
        return (int) count;
6,272,354✔
1565
}
1566

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

1571
        assert(f);
2,654,951✔
1572

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

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

1588
        return r > 0;          /* Return 1 if something was read. */
2,654,951✔
1589
}
1590

1591
int safe_fgetc(FILE *f, char *ret) {
204,269,565✔
1592
        int k;
204,269,565✔
1593

1594
        assert(f);
204,269,565✔
1595

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

1600
        errno = 0;
204,269,565✔
1601
        k = fgetc(f);
204,269,565✔
1602
        if (k == EOF) {
204,269,565✔
1603
                if (ferror(f))
466,817✔
1604
                        return errno_or_else(EIO);
44✔
1605

1606
                if (ret)
466,795✔
1607
                        *ret = 0;
466,721✔
1608

1609
                return 0;
466,795✔
1610
        }
1611

1612
        if (ret)
203,802,748✔
1613
                *ret = k;
203,802,748✔
1614

1615
        return 1;
1616
}
1617

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

1621
        if (!filename)
152✔
1622
                return 0;
152✔
1623

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

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

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