]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/fileio.c
update NEWS with even more features for v258
[thirdparty/systemd.git] / src / basic / fileio.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a5c32cff 2
11c3a366 3#include <fcntl.h>
35bbbf85 4#include <stdio_ext.h>
11c3a366 5#include <stdlib.h>
11c3a366 6#include <sys/stat.h>
a5c32cff 7#include <unistd.h>
cda134ab 8
b5efdb8a 9#include "alloc-util.h"
0c15577a 10#include "errno-util.h"
ad9a66fe 11#include "extract-word.h"
3ffd4af2
LP
12#include "fd-util.h"
13#include "fileio.h"
f4f15635 14#include "fs-util.h"
07d8c0eb 15#include "hexdecoct.h"
8eeb8709 16#include "label.h"
93cc7779 17#include "log.h"
50ccd864 18#include "mkdir.h"
08af3cc5 19#include "nulstr-util.h"
33d52ab9 20#include "parse-util.h"
0d39fa9c 21#include "path-util.h"
b93d3f6b 22#include "socket-util.h"
0c15577a 23#include "stat-util.h"
33d52ab9 24#include "stdio-util.h"
07630cea 25#include "string-util.h"
d9ccf6b3 26#include "strv.h"
bf819d3a 27#include "sync-util.h"
dd9c8da8 28#include "terminal-util.h"
0c15577a 29#include "time-util.h"
e4de7287 30#include "tmpfile-util.h"
a5c32cff 31
f6dd48fa 32/* The maximum size of the file we'll read in one go in read_full_file() (64M). */
faadc90c 33#define READ_FULL_BYTES_MAX (64U * U64_MB - UINT64_C(1))
7e2a5fbd
YW
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
f6dd48fa 36
7ab7547a
LP
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. */
faadc90c 46#define READ_VIRTUAL_BYTES_MAX (4U * U64_MB - UINT64_C(2))
c2d11a63 47
02e23d1a
ZJS
48int fdopen_unlocked(int fd, const char *options, FILE **ret) {
49 assert(ret);
50
51 FILE *f = fdopen(fd, options);
52 if (!f)
53 return -errno;
54
55 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
56
57 *ret = f;
58 return 0;
59}
60
3ebbb6cb 61int take_fdopen_unlocked(int *fd, const char *options, FILE **ret) {
6604fb02 62 int r;
3ebbb6cb
VC
63
64 assert(fd);
65
66 r = fdopen_unlocked(*fd, options, ret);
67 if (r < 0)
68 return r;
69
254d1313 70 *fd = -EBADF;
3ebbb6cb
VC
71
72 return 0;
73}
74
75FILE* take_fdopen(int *fd, const char *options) {
76 assert(fd);
77
78 FILE *f = fdopen(*fd, options);
79 if (!f)
80 return NULL;
81
254d1313 82 *fd = -EBADF;
3ebbb6cb
VC
83
84 return f;
85}
86
f61457b0
VC
87DIR* take_fdopendir(int *dfd) {
88 assert(dfd);
89
90 DIR *d = fdopendir(*dfd);
91 if (!d)
92 return NULL;
93
254d1313 94 *dfd = -EBADF;
f61457b0
VC
95
96 return d;
97}
98
2fe21124
ZJS
99FILE* open_memstream_unlocked(char **ptr, size_t *sizeloc) {
100 FILE *f = open_memstream(ptr, sizeloc);
101 if (!f)
102 return NULL;
103
104 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
105
106 return f;
107}
108
673a1e6f
ZJS
109FILE* fmemopen_unlocked(void *buf, size_t size, const char *mode) {
110 FILE *f = fmemopen(buf, size, mode);
111 if (!f)
112 return NULL;
113
114 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
115
116 return f;
117}
118
8a0adc97 119int write_string_stream_full(
b1837133
LP
120 FILE *f,
121 const char *line,
122 WriteStringFileFlags flags,
4d5f52e7 123 const struct timespec *ts) {
dacd6cee 124
91dc2bf7 125 bool needs_nl;
254d1313 126 int r, fd = -EBADF;
91dc2bf7 127
717603e3
LP
128 assert(f);
129 assert(line);
130
ba8b8c9e
MG
131 if (ferror(f))
132 return -EIO;
133
14f594b9
LP
134 if (ts) {
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);
138 if (fd < 0)
139 return -EBADF;
140 }
141
e565cfd2
ADT
142 if (flags & WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) {
143 _cleanup_free_ char *t = NULL;
144
145 /* If value to be written is same as that of the existing value, then suppress the write. */
146
147 if (fd < 0) {
148 fd = fileno(f);
149 if (fd < 0)
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 &&
157 streq_skip_trailing_chars(line, t, NEWLINE)) {
ba669952 158 log_debug("No change in value '%s', suppressing write", line);
e565cfd2
ADT
159 return 0;
160 }
161
162 if (lseek(fd, 0, SEEK_SET) < 0)
163 return -errno;
164 }
165
91dc2bf7
LP
166 needs_nl = !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) && !endswith(line, "\n");
167
168 if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) {
55e2cfc9
ZJS
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 */
91dc2bf7
LP
171
172 line = strjoina(line, "\n");
173 needs_nl = false;
174 }
175
94d3b60f
MG
176 if (fputs(line, f) == EOF)
177 return -errno;
178
91dc2bf7 179 if (needs_nl)
94d3b60f
MG
180 if (fputc('\n', f) == EOF)
181 return -errno;
a5c32cff 182
be83711c
CL
183 if (flags & WRITE_STRING_FILE_SYNC)
184 r = fflush_sync_and_check(f);
185 else
186 r = fflush_and_check(f);
187 if (r < 0)
188 return r;
189
39c38d77 190 if (ts) {
4d5f52e7 191 const struct timespec twice[2] = {*ts, *ts};
39c38d77 192
55e2cfc9 193 assert(fd >= 0);
14f594b9 194 if (futimens(fd, twice) < 0)
39c38d77
ZJS
195 return -errno;
196 }
197
be83711c 198 return 0;
a5c32cff
HH
199}
200
2148c669
LP
201static mode_t write_string_file_flags_to_mode(WriteStringFileFlags flags) {
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 :
211 FLAGS_SET(flags, WRITE_STRING_FILE_MODE_0444) ? 0444 : 0644;
212}
213
0ab5e2a4
DDM
214static int write_string_file_atomic_at(
215 int dir_fd,
2eabcc77
LP
216 const char *fn,
217 const char *line,
b1837133 218 WriteStringFileFlags flags,
4d5f52e7 219 const struct timespec *ts) {
2eabcc77 220
a5c32cff
HH
221 _cleanup_fclose_ FILE *f = NULL;
222 _cleanup_free_ char *p = NULL;
223 int r;
224
225 assert(fn);
226 assert(line);
227
95244ceb
LP
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
8eeb8709
LP
231 mode_t mode = write_string_file_flags_to_mode(flags);
232
233 bool call_label_ops_post = false;
234 if (FLAGS_SET(flags, WRITE_STRING_FILE_LABEL)) {
235 r = label_ops_pre(dir_fd, fn, mode);
236 if (r < 0)
237 return r;
238
239 call_label_ops_post = true;
240 }
241
0ab5e2a4 242 r = fopen_temporary_at(dir_fd, fn, &f, &p);
42f6a96e
YW
243 if (call_label_ops_post)
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));
a5c32cff 247 if (r < 0)
8eeb8709
LP
248 goto fail;
249
8a0adc97 250 r = write_string_stream_full(f, line, flags, ts);
9dd1b1e8
LP
251 if (r < 0)
252 goto fail;
253
8eeb8709 254 r = fchmod_umask(fileno(f), mode);
95244ceb
LP
255 if (r < 0)
256 goto fail;
257
8eeb8709
LP
258 r = RET_NERRNO(renameat(dir_fd, p, dir_fd, fn));
259 if (r < 0)
9dd1b1e8 260 goto fail;
a5c32cff 261
5b3f4a20
LP
262 if (FLAGS_SET(flags, WRITE_STRING_FILE_SYNC)) {
263 /* Sync the rename, too */
264 r = fsync_directory_of_file(fileno(f));
265 if (r < 0)
266 return r;
267 }
268
9dd1b1e8 269 return 0;
a5c32cff 270
9dd1b1e8 271fail:
8eeb8709
LP
272 if (f)
273 (void) unlinkat(dir_fd, p, 0);
a5c32cff
HH
274 return r;
275}
276
8a0adc97 277int write_string_file_full(
0ab5e2a4 278 int dir_fd,
b1837133
LP
279 const char *fn,
280 const char *line,
281 WriteStringFileFlags flags,
bbec1c87 282 const struct timespec *ts,
283 const char *label_fn) {
b1837133 284
42f6a96e 285 bool made_file = false;
4c1fc3e4 286 _cleanup_fclose_ FILE *f = NULL;
0f585d41 287 _cleanup_close_ int fd = -EBADF;
8eeb8709 288 int r;
4c1fc3e4 289
f3c5c2b0 290 assert(dir_fd == AT_FDCWD || dir_fd >= 0);
4c1fc3e4
DM
291 assert(line);
292
265710c2
AJ
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)));
0675e94a 295
50ccd864 296 if (flags & WRITE_STRING_FILE_MKDIR_0755) {
f3c5c2b0
YW
297 assert(fn);
298
0ab5e2a4 299 r = mkdirat_parents(dir_fd, fn, 0755);
50ccd864
LP
300 if (r < 0)
301 return r;
302 }
303
4c1fc3e4 304 if (flags & WRITE_STRING_FILE_ATOMIC) {
f3c5c2b0 305 assert(fn);
4c1fc3e4
DM
306 assert(flags & WRITE_STRING_FILE_CREATE);
307
0ab5e2a4 308 r = write_string_file_atomic_at(dir_fd, fn, line, flags, ts);
eb3da901
LP
309 if (r < 0)
310 goto fail;
311
312 return r;
8eeb8709
LP
313 }
314
f3c5c2b0
YW
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))
42f6a96e
YW
317 r = fd = fd_reopen(
318 ASSERT_FD(dir_fd), O_CLOEXEC | O_NOCTTY |
319 (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
4fe348cf
DDM
320 (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY) |
321 (FLAGS_SET(flags, WRITE_STRING_FILE_OPEN_NONBLOCKING) ? O_NONBLOCK : 0));
f3c5c2b0
YW
322 else {
323 mode_t mode = write_string_file_flags_to_mode(flags);
42f6a96e 324 bool call_label_ops_post = false;
f3c5c2b0
YW
325
326 if (FLAGS_SET(flags, WRITE_STRING_FILE_LABEL|WRITE_STRING_FILE_CREATE)) {
327 r = label_ops_pre(dir_fd, label_fn ?: fn, mode);
328 if (r < 0)
329 goto fail;
330
331 call_label_ops_post = true;
332 }
8eeb8709 333
42f6a96e 334 r = fd = openat_report_new(
f3c5c2b0
YW
335 dir_fd, fn, O_CLOEXEC | O_NOCTTY |
336 (FLAGS_SET(flags, WRITE_STRING_FILE_NOFOLLOW) ? O_NOFOLLOW : 0) |
337 (FLAGS_SET(flags, WRITE_STRING_FILE_CREATE) ? O_CREAT : 0) |
338 (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
4fe348cf
DDM
339 (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY) |
340 (FLAGS_SET(flags, WRITE_STRING_FILE_OPEN_NONBLOCKING) ? O_NONBLOCK : 0),
f3c5c2b0
YW
341 mode,
342 &made_file);
42f6a96e
YW
343 if (call_label_ops_post)
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));
8eeb8709 347 }
42f6a96e 348 if (r < 0)
95244ceb 349 goto fail;
8eeb8709 350
0f585d41
YW
351 r = take_fdopen_unlocked(&fd, "w", &f);
352 if (r < 0)
95244ceb 353 goto fail;
35bbbf85 354
12ec9c30
TSH
355 if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
356 setvbuf(f, NULL, _IONBF, 0);
357
8a0adc97 358 r = write_string_stream_full(f, line, flags, ts);
eb3da901
LP
359 if (r < 0)
360 goto fail;
361
362 return 0;
363
364fail:
aec1262a
LP
365 if (made_file)
366 (void) unlinkat(dir_fd, fn, 0);
8eeb8709 367
eb3da901
LP
368 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
369 return r;
370
371 f = safe_fclose(f);
8eeb8709 372 fd = safe_close(fd);
eb3da901 373
8eeb8709
LP
374 /* OK, the operation failed, but let's see if the right contents in place already. If so, eat up the
375 * error. */
9e096259 376 if (verify_file_at(dir_fd, fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) || (flags & WRITE_STRING_FILE_VERIFY_IGNORE_NEWLINE)) > 0)
8eeb8709 377 return 0;
eb3da901 378
8eeb8709 379 return r;
4c1fc3e4
DM
380}
381
3130fca5
LP
382int write_string_filef(
383 const char *fn,
384 WriteStringFileFlags flags,
385 const char *format, ...) {
386
387 _cleanup_free_ char *p = NULL;
388 va_list ap;
389 int r;
390
391 va_start(ap, format);
392 r = vasprintf(&p, format, ap);
393 va_end(ap);
394
395 if (r < 0)
396 return -ENOMEM;
397
398 return write_string_file(fn, p, flags);
399}
400
dc163cd4
LP
401int write_base64_file_at(
402 int dir_fd,
403 const char *fn,
404 const struct iovec *data,
405 WriteStringFileFlags flags) {
406
407 _cleanup_free_ char *encoded = NULL;
408 ssize_t n;
409
410 n = base64mem_full(data ? data->iov_base : NULL, data ? data->iov_len : 0, 79, &encoded);
411 if (n < 0)
412 return n;
413
414 return write_string_file_at(dir_fd, fn, encoded, flags);
415}
416
46b457e5 417int read_one_line_file_at(int dir_fd, const char *filename, char **ret) {
a5c32cff 418 _cleanup_fclose_ FILE *f = NULL;
fdeea3f4 419 int r;
a5c32cff 420
46b457e5
YW
421 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
422 assert(filename);
423 assert(ret);
a5c32cff 424
46b457e5 425 r = fopen_unlocked_at(dir_fd, filename, "re", 0, &f);
fdeea3f4
ZJS
426 if (r < 0)
427 return r;
35bbbf85 428
46b457e5 429 return read_line(f, LONG_LINE_MAX, ret);
a5c32cff
HH
430}
431
0ab5e2a4 432int verify_file_at(int dir_fd, const char *fn, const char *blob, bool accept_extra_nl) {
eb3da901
LP
433 _cleanup_fclose_ FILE *f = NULL;
434 _cleanup_free_ char *buf = NULL;
435 size_t l, k;
fdeea3f4 436 int r;
15dee3f0 437
eb3da901
LP
438 assert(blob);
439
440 l = strlen(blob);
441
442 if (accept_extra_nl && endswith(blob, "\n"))
443 accept_extra_nl = false;
444
445 buf = malloc(l + accept_extra_nl + 1);
446 if (!buf)
447 return -ENOMEM;
448
f3c5c2b0 449 r = fopen_unlocked_at(dir_fd, strempty(fn), "re", 0, &f);
fdeea3f4
ZJS
450 if (r < 0)
451 return r;
35bbbf85 452
eb3da901
LP
453 /* We try to read one byte more than we need, so that we know whether we hit eof */
454 errno = 0;
455 k = fread(buf, 1, l + accept_extra_nl + 1, f);
456 if (ferror(f))
66855de7 457 return errno_or_else(EIO);
eb3da901
LP
458
459 if (k != l && k != l + accept_extra_nl)
460 return 0;
461 if (memcmp(buf, blob, l) != 0)
462 return 0;
463 if (k > l && buf[l] != '\n')
464 return 0;
15dee3f0 465
eb3da901 466 return 1;
15dee3f0
LP
467}
468
06503dd0
YW
469int read_virtual_file_at(
470 int dir_fd,
471 const char *filename,
472 size_t max_size,
473 char **ret_contents,
474 size_t *ret_size) {
475
21b40f16 476 _cleanup_free_ char *buf = NULL;
21b40f16
FB
477 size_t n, size;
478 int n_retries;
61977664 479 bool truncated = false;
21b40f16 480
ad0e687c
ZJS
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
259f6de4
LP
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
da65941c
LP
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 */
21b40f16 497
06503dd0 498 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
f6dd48fa 499 assert(max_size <= READ_VIRTUAL_BYTES_MAX || max_size == SIZE_MAX);
ad0e687c 500
06503dd0
YW
501 _cleanup_close_ int fd = -EBADF;
502 if (isempty(filename))
503 fd = fd_reopen(ASSERT_FD(dir_fd), O_RDONLY | O_NOCTTY | O_CLOEXEC);
504 else
505 fd = RET_NERRNO(openat(dir_fd, filename, O_RDONLY | O_NOCTTY | O_CLOEXEC));
506 if (fd < 0)
507 return fd;
508
21b40f16
FB
509 /* Limit the number of attempts to read the number of bytes returned by fstat(). */
510 n_retries = 3;
511
512 for (;;) {
ad0e687c
ZJS
513 struct stat st;
514
21b40f16
FB
515 if (fstat(fd, &st) < 0)
516 return -errno;
517
518 if (!S_ISREG(st.st_mode))
519 return -EBADF;
520
521 /* Be prepared for files from /proc which generally report a file size of 0. */
f6dd48fa 522 assert_cc(READ_VIRTUAL_BYTES_MAX < SSIZE_MAX);
b2d0b90f
LP
523 if (st.st_size > 0 && n_retries > 1) {
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
1b5e91a8 527 if (st.st_size > SSIZE_MAX) { /* Avoid overflow with 32-bit size_t and 64-bit off_t. */
ad0e687c 528
1b5e91a8
LP
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);
535
f6dd48fa 536 if (size > READ_VIRTUAL_BYTES_MAX)
1b5e91a8
LP
537 return -EFBIG;
538 }
c5384931 539
21b40f16 540 n_retries--;
5aaa55d8 541 } else if (n_retries > 1) {
46a0f5ca
ADT
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. */
5aaa55d8
AZ
544 size = MIN3(page_size() - 1, READ_VIRTUAL_BYTES_MAX, max_size);
545 n_retries = 1;
ca795643 546 } else {
f6dd48fa 547 size = MIN(READ_VIRTUAL_BYTES_MAX, max_size);
2ac67221 548 n_retries = 0;
ca795643 549 }
21b40f16 550
b235b031
LP
551 buf = malloc(size + 1);
552 if (!buf)
21b40f16 553 return -ENOMEM;
b2d0b90f 554
2ac67221 555 /* Use a bigger allocation if we got it anyway, but not more than the limit. */
f6dd48fa 556 size = MIN3(MALLOC_SIZEOF_SAFE(buf) - 1, max_size, READ_VIRTUAL_BYTES_MAX);
21b40f16
FB
557
558 for (;;) {
559 ssize_t k;
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);
565 if (k >= 0) {
566 n = k;
567 break;
568 }
569
6b8664cb 570 if (errno != EINTR)
21b40f16
FB
571 return -errno;
572 }
573
574 /* Consider a short read as EOF */
575 if (n <= size)
576 break;
577
00bd9a4a
LP
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) {
584 n = size; /* Make sure we never use more than what we sized the buffer for (so that
0b75493d 585 * we have one free byte in it for the trailing NUL we add below). */
136f12a2
LP
586 truncated = true;
587 break;
588 }
589
b2d0b90f
LP
590 /* We have no further attempts left? Then the file is apparently larger than our limits. Give up. */
591 if (n_retries <= 0)
592 return -EFBIG;
ad0e687c 593
b2d0b90f
LP
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. */
2ac67221 597
21b40f16
FB
598 if (lseek(fd, 0, SEEK_SET) < 0)
599 return -errno;
b235b031
LP
600
601 buf = mfree(buf);
21b40f16
FB
602 }
603
fd3c6992 604 if (ret_contents) {
b235b031 605
a9899ff3
ZJS
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. */
fd3c6992
LP
609 if (!ret_size && memchr(buf, 0, n))
610 return -EBADMSG;
21b40f16 611
fd3c6992
LP
612 if (n < size) {
613 char *p;
f267c314 614
fd3c6992
LP
615 /* Return rest of the buffer to libc */
616 p = realloc(buf, n + 1);
617 if (!p)
618 return -ENOMEM;
619 buf = p;
620 }
621
622 buf[n] = 0;
f267c314 623 *ret_contents = TAKE_PTR(buf);
fd3c6992
LP
624 }
625
626 if (ret_size)
627 *ret_size = n;
21b40f16 628
61977664 629 return !truncated;
21b40f16
FB
630}
631
15f8f026 632int read_full_stream_full(
2d78717b 633 FILE *f,
50caae7b 634 const char *filename,
986311c2
LP
635 uint64_t offset,
636 size_t size,
15f8f026 637 ReadFullFileFlags flags,
2d78717b
LP
638 char **ret_contents,
639 size_t *ret_size) {
640
a5c32cff 641 _cleanup_free_ char *buf = NULL;
7e2a5fbd 642 size_t n, n_next = 0, l, expected_decoded_size = size;
15f8f026 643 int fd, r;
a5c32cff 644
717603e3 645 assert(f);
2d78717b 646 assert(ret_contents);
89aaf655 647 assert(!FLAGS_SET(flags, READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX));
7b0da71d 648 assert(size != SIZE_MAX || !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER));
a5c32cff 649
7b0da71d 650 if (offset != UINT64_MAX && offset > LONG_MAX) /* fseek() can only deal with "long" offsets */
986311c2
LP
651 return -ERANGE;
652
7e2a5fbd
YW
653 if ((flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) != 0) {
654 if (size <= SIZE_MAX / READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY)
655 size *= READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY;
656 else
657 size = SIZE_MAX;
658 }
659
c4054ddf 660 fd = fileno(f);
986311c2
LP
661 if (fd >= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see
662 * fmemopen()), let's optimize our buffering */
663 struct stat st;
717603e3 664
15f8f026 665 if (fstat(fd, &st) < 0)
c4054ddf
LP
666 return -errno;
667
668 if (S_ISREG(st.st_mode)) {
7b0da71d
LP
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 &&
677 (size == SIZE_MAX || FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER))) {
678
986311c2
LP
679 uint64_t rsize =
680 LESS_BY((uint64_t) st.st_size, offset == UINT64_MAX ? 0 : offset);
681
7b0da71d 682 if (rsize < SIZE_MAX) /* overflow check */
986311c2
LP
683 n_next = rsize + 1;
684 }
50caae7b 685
f2944702 686 if (flags & READ_FULL_FILE_WARN_WORLD_READABLE)
50caae7b 687 (void) warn_file_is_world_accessible(filename, &st, NULL, 0);
c4054ddf 688 }
717603e3 689 }
a5c32cff 690
7b0da71d
LP
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)
696 n_next = size != SIZE_MAX && !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) ? size : LINE_MAX;
697
698 /* Never read more than we need to determine that our own limit is hit */
699 if (n_next > READ_FULL_BYTES_MAX)
700 n_next = READ_FULL_BYTES_MAX + 1;
701
986311c2
LP
702 if (offset != UINT64_MAX && fseek(f, offset, SEEK_SET) < 0)
703 return -errno;
704
15f8f026 705 n = l = 0;
a5c32cff
HH
706 for (;;) {
707 char *t;
708 size_t k;
709
7b0da71d 710 /* If we shall fail when reading overly large data, then read exactly one byte more than the
d7306348 711 * specified size at max, since that'll tell us if there's anymore data beyond the limit. */
7b0da71d
LP
712 if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && n_next > size)
713 n_next = size + 1;
714
15f8f026
YW
715 if (flags & READ_FULL_FILE_SECURE) {
716 t = malloc(n_next + 1);
717 if (!t) {
718 r = -ENOMEM;
719 goto finalize;
720 }
721 memcpy_safe(t, buf, n);
722 explicit_bzero_safe(buf, n);
f6dd48fa 723 free(buf);
15f8f026
YW
724 } else {
725 t = realloc(buf, n_next + 1);
726 if (!t)
727 return -ENOMEM;
728 }
a5c32cff
HH
729
730 buf = t;
a60d0647
LP
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) */
6df28e1f 733 n = size == SIZE_MAX ? MALLOC_SIZEOF_SAFE(buf) - 1 : n_next;
15f8f026 734
5a89faf0 735 errno = 0;
a5c32cff 736 k = fread(buf + l, 1, n - l, f);
b93d3f6b
LP
737
738 assert(k <= n - l);
739 l += k;
a5c32cff 740
15f8f026 741 if (ferror(f)) {
66855de7 742 r = errno_or_else(EIO);
15f8f026
YW
743 goto finalize;
744 }
c2d11a63 745 if (feof(f))
a5c32cff 746 break;
a5c32cff 747
7b0da71d 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 */
986311c2
LP
749 assert(l == size);
750 break;
751 }
752
b93d3f6b 753 assert(k > 0); /* we can't have read zero bytes because that would have been EOF */
a5c32cff 754
7b0da71d
LP
755 if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && l > size) {
756 r = -E2BIG;
757 goto finalize;
758 }
759
15f8f026
YW
760 if (n >= READ_FULL_BYTES_MAX) {
761 r = -E2BIG;
762 goto finalize;
763 }
c2d11a63 764
15f8f026 765 n_next = MIN(n * 2, READ_FULL_BYTES_MAX);
a5c32cff
HH
766 }
767
89aaf655 768 if (flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) {
c668aa8b
LP
769 _cleanup_free_ void *decoded = NULL;
770 size_t decoded_size;
771
07d8c0eb 772 buf[l++] = 0;
89aaf655 773 if (flags & READ_FULL_FILE_UNBASE64)
c668aa8b 774 r = unbase64mem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size);
89aaf655 775 else
c668aa8b
LP
776 r = unhexmem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size);
777 if (r < 0)
778 goto finalize;
779
780 if (flags & READ_FULL_FILE_SECURE)
781 explicit_bzero_safe(buf, n);
782 free_and_replace(buf, decoded);
783 n = l = decoded_size;
7e2a5fbd
YW
784
785 if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && l > expected_decoded_size) {
786 r = -E2BIG;
787 goto finalize;
788 }
07d8c0eb
YW
789 }
790
2d78717b
LP
791 if (!ret_size) {
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
15f8f026
YW
796 if (memchr(buf, 0, l)) {
797 r = -EBADMSG;
798 goto finalize;
799 }
2d78717b
LP
800 }
801
a5c32cff 802 buf[l] = 0;
2d78717b 803 *ret_contents = TAKE_PTR(buf);
a5c32cff 804
2d78717b
LP
805 if (ret_size)
806 *ret_size = l;
a5c32cff
HH
807
808 return 0;
15f8f026
YW
809
810finalize:
811 if (flags & READ_FULL_FILE_SECURE)
812 explicit_bzero_safe(buf, n);
813
814 return r;
a5c32cff
HH
815}
816
d3dcf4e3
LP
817int read_full_file_full(
818 int dir_fd,
819 const char *filename,
986311c2
LP
820 uint64_t offset,
821 size_t size,
d3dcf4e3
LP
822 ReadFullFileFlags flags,
823 const char *bind_name,
986311c2
LP
824 char **ret_contents,
825 size_t *ret_size) {
d3dcf4e3 826
717603e3 827 _cleanup_fclose_ FILE *f = NULL;
61d9982c 828 XfopenFlags xflags = XFOPEN_UNLOCKED;
fdeea3f4 829 int r;
717603e3 830
15f8f026 831 assert(filename);
986311c2 832 assert(ret_contents);
717603e3 833
61d9982c
YW
834 if (FLAGS_SET(flags, READ_FULL_FILE_CONNECT_SOCKET) && /* If this is enabled, let's try to connect to it */
835 offset == UINT64_MAX) /* Seeking is not supported on AF_UNIX sockets */
836 xflags |= XFOPEN_SOCKET;
986311c2 837
61d9982c
YW
838 r = xfopenat_full(dir_fd, filename, "re", 0, xflags, bind_name, &f);
839 if (r < 0)
840 return r;
8241f785 841
986311c2 842 return read_full_stream_full(f, filename, offset, size, flags, ret_contents, ret_size);
717603e3
LP
843}
844
ad9a66fe
MY
845int script_get_shebang_interpreter(const char *path, char **ret) {
846 _cleanup_fclose_ FILE *f = NULL;
99c61f6b 847 int r;
68fee104
ZJS
848
849 assert(path);
850
ad9a66fe
MY
851 f = fopen(path, "re");
852 if (!f)
853 return -errno;
854
855 char c;
856 r = safe_fgetc(f, &c);
68fee104
ZJS
857 if (r < 0)
858 return r;
ad9a66fe
MY
859 if (r == 0)
860 return -EBADMSG;
861 if (c != '#')
862 return -EMEDIUMTYPE;
863 r = safe_fgetc(f, &c);
864 if (r < 0)
865 return r;
866 if (r == 0)
867 return -EBADMSG;
868 if (c != '!')
869 return -EMEDIUMTYPE;
68fee104 870
ad9a66fe
MY
871 _cleanup_free_ char *line = NULL;
872 r = read_line(f, LONG_LINE_MAX, &line);
873 if (r < 0)
874 return r;
68fee104 875
ad9a66fe
MY
876 _cleanup_free_ char *p = NULL;
877 const char *s = line;
68fee104 878
ad9a66fe
MY
879 r = extract_first_word(&s, &p, /* separators = */ NULL, /* flags = */ 0);
880 if (r < 0)
881 return r;
882 if (r == 0)
883 return -ENOEXEC;
68fee104 884
ad9a66fe
MY
885 if (ret)
886 *ret = TAKE_PTR(p);
887 return 0;
68fee104 888}
69ab8088 889
15036f85
MY
890int get_proc_field(const char *path, const char *key, char **ret) {
891 _cleanup_fclose_ FILE *f = NULL;
69ab8088
ZJS
892 int r;
893
15036f85
MY
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);
900 assert(key);
69ab8088 901
15036f85
MY
902 r = fopen_unlocked(path, "re", &f);
903 if (r == -ENOENT && proc_mounted() == 0)
904 return -ENOSYS;
69ab8088
ZJS
905 if (r < 0)
906 return r;
907
15036f85
MY
908 for (;;) {
909 _cleanup_free_ char *line = NULL;
910
911 r = read_line(f, LONG_LINE_MAX, &line);
912 if (r < 0)
913 return r;
914 if (r == 0)
915 return -ENODATA;
916
917 char *l = startswith(line, key);
918 if (l && *l == ':') {
919 if (ret) {
920 char *s = strdupcspn(skip_leading_chars(l + 1, " \t"), WHITESPACE);
921 if (!s)
922 return -ENOMEM;
923
924 *ret = s;
925 }
926
927 return 0;
928 }
4ec29144 929 }
69ab8088 930}
0d39fa9c 931
c0cf1c58
MY
932DIR* xopendirat(int dir_fd, const char *name, int flags) {
933 _cleanup_close_ int fd = -EBADF;
0d39fa9c 934
c0cf1c58
MY
935 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
936 assert(name);
937 assert(!(flags & (O_CREAT|O_TMPFILE)));
0d39fa9c 938
c0cf1c58 939 if (dir_fd == AT_FDCWD && flags == 0)
823d72c7
LP
940 return opendir(name);
941
c0cf1c58
MY
942 fd = openat(dir_fd, name, O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
943 if (fd < 0)
0d39fa9c
LP
944 return NULL;
945
c0cf1c58 946 return take_fdopendir(&fd);
0d39fa9c
LP
947}
948
01bebba3 949int fopen_mode_to_flags(const char *mode) {
0a38e6b9
LP
950 const char *p;
951 int flags;
952
01bebba3
LP
953 assert(mode);
954
0a38e6b9
LP
955 if ((p = startswith(mode, "r+")))
956 flags = O_RDWR;
957 else if ((p = startswith(mode, "r")))
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;
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++) {
971
972 switch (*p) {
973
974 case 'e':
975 flags |= O_CLOEXEC;
976 break;
977
978 case 'x':
979 flags |= O_EXCL;
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
61d9982c 995static int xfopenat_regular(int dir_fd, const char *path, const char *mode, int open_flags, FILE **ret) {
0a38e6b9
LP
996 FILE *f;
997
998 /* A combination of fopen() with openat() */
999
0f585d41
YW
1000 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1001 assert(path);
1002 assert(mode);
1003 assert(ret);
1004
61d9982c 1005 if (dir_fd == AT_FDCWD && open_flags == 0)
0a38e6b9 1006 f = fopen(path, mode);
0f585d41
YW
1007 else {
1008 _cleanup_close_ int fd = -EBADF;
1009 int mode_flags;
0a38e6b9 1010
01bebba3 1011 mode_flags = fopen_mode_to_flags(mode);
0a38e6b9
LP
1012 if (mode_flags < 0)
1013 return mode_flags;
1014
61d9982c 1015 fd = openat(dir_fd, path, mode_flags | open_flags);
0a38e6b9
LP
1016 if (fd < 0)
1017 return -errno;
1018
0f585d41 1019 f = take_fdopen(&fd, mode);
0a38e6b9 1020 }
0f585d41
YW
1021 if (!f)
1022 return -errno;
0a38e6b9
LP
1023
1024 *ret = f;
1025 return 0;
1026}
1027
61d9982c
YW
1028static int xfopenat_unix_socket(int dir_fd, const char *path, const char *bind_name, FILE **ret) {
1029 _cleanup_close_ int sk = -EBADF;
1030 FILE *f;
1031 int r;
1032
1033 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1034 assert(path);
1035 assert(ret);
1036
1037 sk = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
1038 if (sk < 0)
1039 return -errno;
1040
1041 if (bind_name) {
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;
1046
1047 r = sockaddr_un_set_path(&bsa.un, bind_name);
1048 if (r < 0)
1049 return r;
1050
1051 if (bind(sk, &bsa.sa, r) < 0)
0a38e6b9 1052 return -errno;
0a38e6b9
LP
1053 }
1054
61d9982c
YW
1055 r = connect_unix_path(sk, dir_fd, path);
1056 if (r < 0)
1057 return r;
1058
1059 if (shutdown(sk, SHUT_WR) < 0)
1060 return -errno;
1061
1062 f = take_fdopen(&sk, "r");
1063 if (!f)
1064 return -errno;
1065
1066 *ret = f;
1067 return 0;
1068}
1069
1070int xfopenat_full(
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 */
1080 int r;
1081
1082 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1083 assert(path);
1084 assert(mode);
1085 assert(ret);
1086
1087 r = xfopenat_regular(dir_fd, path, mode, open_flags, &f);
1088 if (r == -ENXIO && FLAGS_SET(flags, XFOPEN_SOCKET)) {
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);
1091 if (IN_SET(r, -ENOTSOCK, -EINVAL))
1092 return -ENXIO; /* propagate original error if this is not a socket after all */
1093 }
1094 if (r < 0)
1095 return r;
1096
1097 if (FLAGS_SET(flags, XFOPEN_UNLOCKED))
1098 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
1099
0a38e6b9
LP
1100 *ret = f;
1101 return 0;
1102}
1103
b839101a
LP
1104int fdopen_independent(int fd, const char *mode, FILE **ret) {
1105 _cleanup_close_ int copy_fd = -EBADF;
1106 _cleanup_fclose_ FILE *f = NULL;
1107 int mode_flags;
1108
1109 assert(fd >= 0);
1110 assert(mode);
1111 assert(ret);
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);
1117 if (mode_flags < 0)
1118 return mode_flags;
1119
6f9677bc
MY
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);
b839101a
LP
1123 if (copy_fd < 0)
1124 return copy_fd;
1125
0f585d41 1126 f = take_fdopen(&copy_fd, mode);
b839101a
LP
1127 if (!f)
1128 return -errno;
1129
b839101a
LP
1130 *ret = TAKE_PTR(f);
1131 return 0;
1132}
1133
2c07d314 1134static int search_and_open_internal(
2708160c 1135 const char *path,
2c07d314 1136 int mode, /* if ret_fd is NULL this is an [FRWX]_OK mode for access(), otherwise an open mode for open() */
2708160c
LP
1137 const char *root,
1138 char **search,
2c07d314 1139 int *ret_fd,
2708160c
LP
1140 char **ret_path) {
1141
2c07d314
LP
1142 int r;
1143
1144 assert(!ret_fd || !FLAGS_SET(mode, O_CREAT)); /* We don't support O_CREAT for this */
0d39fa9c 1145 assert(path);
2c07d314
LP
1146
1147 if (path_is_absolute(path)) {
1148 _cleanup_close_ int fd = -EBADF;
1149
1150 if (ret_fd)
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));
1154 else
1155 r = RET_NERRNO(access(path, mode));
1156 if (r < 0)
1157 return r;
1158
1159 if (ret_path) {
1160 r = path_simplify_alloc(path, ret_path);
1161 if (r < 0)
1162 return r;
1163 }
1164
1165 if (ret_fd)
1166 *ret_fd = TAKE_FD(fd);
1167
1168 return 0;
1169 }
0d39fa9c
LP
1170
1171 if (!path_strv_resolve_uniq(search, root))
1172 return -ENOMEM;
1173
1174 STRV_FOREACH(i, search) {
2c07d314 1175 _cleanup_close_ int fd = -EBADF;
0d39fa9c 1176 _cleanup_free_ char *p = NULL;
0d39fa9c 1177
657ee2d8 1178 p = path_join(root, *i, path);
0d39fa9c
LP
1179 if (!p)
1180 return -ENOMEM;
1181
2c07d314
LP
1182 if (ret_fd)
1183 /* as above, 0777 is static analyzer appeasement */
1184 r = fd = RET_NERRNO(open(p, mode, 0777));
1185 else
1186 r = RET_NERRNO(access(p, F_OK));
1187 if (r >= 0) {
2708160c 1188 if (ret_path)
4ff361cc 1189 *ret_path = path_simplify(TAKE_PTR(p));
2708160c 1190
2c07d314
LP
1191 if (ret_fd)
1192 *ret_fd = TAKE_FD(fd);
1193
0d39fa9c
LP
1194 return 0;
1195 }
2c07d314
LP
1196 if (r != -ENOENT)
1197 return r;
0d39fa9c
LP
1198 }
1199
1200 return -ENOENT;
1201}
1202
2c07d314
LP
1203int search_and_open(
1204 const char *path,
1205 int mode,
2708160c 1206 const char *root,
2c07d314
LP
1207 char **search,
1208 int *ret_fd,
2708160c
LP
1209 char **ret_path) {
1210
0d39fa9c
LP
1211 _cleanup_strv_free_ char **copy = NULL;
1212
2c07d314 1213 assert(path);
0d39fa9c 1214
2c07d314
LP
1215 copy = strv_copy((char**) search);
1216 if (!copy)
1217 return -ENOMEM;
0d39fa9c 1218
2c07d314
LP
1219 return search_and_open_internal(path, mode, root, copy, ret_fd, ret_path);
1220}
1221
1222static int search_and_fopen_internal(
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;
1231 _cleanup_close_ int fd = -EBADF;
1232 int r;
1233
1234 assert(path);
1235 assert(mode || !ret_file);
1236
1237 r = search_and_open(
1238 path,
1239 mode ? fopen_mode_to_flags(mode) : 0,
1240 root,
1241 search,
1242 ret_file ? &fd : NULL,
1243 ret_path ? &found_path : NULL);
1244 if (r < 0)
1245 return r;
1246
1247 if (ret_file) {
1248 FILE *f = take_fdopen(&fd, mode);
2708160c
LP
1249 if (!f)
1250 return -errno;
1251
2c07d314 1252 *ret_file = f;
0d39fa9c
LP
1253 }
1254
2c07d314
LP
1255 if (ret_path)
1256 *ret_path = TAKE_PTR(found_path);
1257
1258 return 0;
1259}
1260
1261int search_and_fopen(
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;
1270
1271 assert(path);
1272 assert(mode || !ret_file);
1273
0d39fa9c
LP
1274 copy = strv_copy((char**) search);
1275 if (!copy)
1276 return -ENOMEM;
1277
2c07d314 1278 return search_and_fopen_internal(path, mode, root, copy, ret_file, ret_path);
0d39fa9c
LP
1279}
1280
2708160c 1281int search_and_fopen_nulstr(
2c07d314 1282 const char *path,
2708160c
LP
1283 const char *mode,
1284 const char *root,
1285 const char *search,
2c07d314 1286 FILE **ret_file,
2708160c
LP
1287 char **ret_path) {
1288
2c07d314 1289 _cleanup_strv_free_ char **l = NULL;
0d39fa9c 1290
2c07d314
LP
1291 assert(path);
1292 assert(mode || !ret_file);
0d39fa9c 1293
2c07d314
LP
1294 l = strv_split_nulstr(search);
1295 if (!l)
0d39fa9c
LP
1296 return -ENOMEM;
1297
2c07d314 1298 return search_and_fopen_internal(path, mode, root, l, ret_file, ret_path);
0d39fa9c
LP
1299}
1300
0d39fa9c
LP
1301int fflush_and_check(FILE *f) {
1302 assert(f);
1303
1304 errno = 0;
1305 fflush(f);
1306
1307 if (ferror(f))
66855de7 1308 return errno_or_else(EIO);
0d39fa9c
LP
1309
1310 return 0;
1311}
1312
0675e94a 1313int fflush_sync_and_check(FILE *f) {
14f594b9 1314 int r, fd;
0675e94a
AJ
1315
1316 assert(f);
1317
1318 r = fflush_and_check(f);
1319 if (r < 0)
1320 return r;
1321
14f594b9
LP
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);
1325 if (fd < 0)
1326 return 0;
1327
bf819d3a 1328 r = fsync_full(fd);
8ac2f74f
LP
1329 if (r < 0)
1330 return r;
1331
0675e94a
AJ
1332 return 0;
1333}
1334
33d52ab9
LP
1335int write_timestamp_file_atomic(const char *fn, usec_t n) {
1336 char ln[DECIMAL_STR_MAX(n)+2];
1337
1338 /* Creates a "timestamp" file, that contains nothing but a
1339 * usec_t timestamp, formatted in ASCII. */
1340
0da36375 1341 if (!timestamp_is_set(n))
33d52ab9
LP
1342 return -ERANGE;
1343
1344 xsprintf(ln, USEC_FMT "\n", n);
1345
1346 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1347}
1348
1349int read_timestamp_file(const char *fn, usec_t *ret) {
1350 _cleanup_free_ char *ln = NULL;
1351 uint64_t t;
1352 int r;
1353
1354 r = read_one_line_file(fn, &ln);
1355 if (r < 0)
1356 return r;
1357
1358 r = safe_atou64(ln, &t);
1359 if (r < 0)
1360 return r;
1361
0da36375 1362 if (!timestamp_is_set(t))
33d52ab9
LP
1363 return -ERANGE;
1364
1365 *ret = (usec_t) t;
1366 return 0;
1367}
d390f8ef 1368
215286a4 1369int fputs_with_separator(FILE *f, const char *s, const char *separator, bool *space) {
d390f8ef 1370 assert(s);
215286a4 1371 assert(space);
d390f8ef 1372
215286a4
MY
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. */
d390f8ef
LP
1377
1378 if (!f)
1379 f = stdout;
1380
215286a4
MY
1381 if (!separator)
1382 separator = " ";
d390f8ef 1383
215286a4
MY
1384 if (*space)
1385 if (fputs(separator, f) < 0)
1386 return -EIO;
d390f8ef 1387
215286a4
MY
1388 *space = true;
1389
1390 if (fputs(s, f) < 0)
1391 return -EIO;
d390f8ef 1392
215286a4 1393 return 0;
d390f8ef 1394}
03532f0a 1395
0160a1db
MY
1396int fputs_with_newline(FILE *f, const char *s) {
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))
1402 return 0;
1403
1404 if (!f)
1405 f = stdout;
1406
1407 if (fputs(s, f) < 0)
1408 return -EIO;
1409
1410 if (endswith(s, "\n"))
1411 return 0;
1412
1413 if (fputc('\n', f) < 0)
1414 return -EIO;
1415
1416 return 1;
1417}
1418
838894b0
LP
1419/* A bitmask of the EOL markers we know */
1420typedef 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
41f11239
LP
1427static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) {
1428
4f06325c 1429 if (!FLAGS_SET(flags, READ_LINE_ONLY_NUL)) {
41f11239
LP
1430 if (c == '\n')
1431 return EOL_TEN;
1432 if (c == '\r')
1433 return EOL_THIRTEEN;
1434 }
1435
838894b0
LP
1436 if (c == '\0')
1437 return EOL_ZERO;
1438
1439 return EOL_NONE;
1440}
1441
fd421c4a 1442DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile, NULL);
f858e514 1443
41f11239 1444int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) {
838894b0 1445 _cleanup_free_ char *buffer = NULL;
319a4f4b 1446 size_t n = 0, count = 0;
609ae0f5 1447 int r;
4f9a66a3
LP
1448
1449 assert(f);
1450
1451 /* Something like a bounded version of getline().
1452 *
838894b0
LP
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
4f9a66a3
LP
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) {
319a4f4b 1476 if (!GREEDY_REALLOC(buffer, 1))
4f9a66a3
LP
1477 return -ENOMEM;
1478 }
1479
f858e514 1480 {
3f691417 1481 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
838894b0 1482 EndOfLineMarker previous_eol = EOL_NONE;
f858e514 1483 flockfile(f);
4f9a66a3 1484
f858e514 1485 for (;;) {
838894b0 1486 EndOfLineMarker eol;
03a7dbea 1487 char c;
4f9a66a3 1488
f858e514
ZJS
1489 if (n >= limit)
1490 return -ENOBUFS;
4f9a66a3 1491
31fd02f0
LP
1492 if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */
1493 return -ENOBUFS;
1494
03a7dbea
LP
1495 r = safe_fgetc(f, &c);
1496 if (r < 0)
1497 return r;
91a306b8 1498 if (r == 0) /* EOF is definitely EOL */
f858e514 1499 break;
4f9a66a3 1500
41f11239 1501 eol = categorize_eol(c, flags);
838894b0
LP
1502
1503 if (FLAGS_SET(previous_eol, EOL_ZERO) ||
1504 (eol == EOL_NONE && previous_eol != EOL_NONE) ||
1505 (eol != EOL_NONE && (previous_eol & eol) != 0)) {
1506 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
517b7760
LP
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);
f858e514 1516 break;
838894b0
LP
1517 }
1518
91a306b8
LP
1519 count++;
1520
838894b0 1521 if (eol != EOL_NONE) {
451fcbfc
LP
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. */
ee41670f 1527
609ae0f5 1528 if ((flags & (READ_LINE_IS_A_TTY|READ_LINE_NOT_A_TTY)) == 0) {
14f594b9
LP
1529 int fd;
1530
1531 fd = fileno(f);
1532 if (fd < 0) /* Maybe an fmemopen() stream? Handle this gracefully,
1533 * and don't call isatty() on an invalid fd */
609ae0f5 1534 flags |= READ_LINE_NOT_A_TTY;
14f594b9 1535 else
dd9c8da8 1536 flags |= isatty_safe(fd) ? READ_LINE_IS_A_TTY : READ_LINE_NOT_A_TTY;
14f594b9 1537 }
609ae0f5 1538 if (FLAGS_SET(flags, READ_LINE_IS_A_TTY))
ee41670f
ZJS
1539 break;
1540 }
1541
1542 if (eol != EOL_NONE) {
838894b0
LP
1543 previous_eol |= eol;
1544 continue;
1545 }
4f9a66a3 1546
f858e514 1547 if (ret) {
319a4f4b 1548 if (!GREEDY_REALLOC(buffer, n + 2))
f858e514 1549 return -ENOMEM;
4f9a66a3 1550
03a7dbea 1551 buffer[n] = c;
4f9a66a3
LP
1552 }
1553
f858e514 1554 n++;
4f9a66a3 1555 }
4f9a66a3
LP
1556 }
1557
4f9a66a3
LP
1558 if (ret) {
1559 buffer[n] = 0;
1560
1cc6c93a 1561 *ret = TAKE_PTR(buffer);
4f9a66a3
LP
1562 }
1563
1564 return (int) count;
1565}
285a9b27 1566
c56cb33f
LP
1567int read_stripped_line(FILE *f, size_t limit, char **ret) {
1568 _cleanup_free_ char *s = NULL;
94b75cdb 1569 int r, k;
c56cb33f
LP
1570
1571 assert(f);
1572
1573 r = read_line(f, limit, ret ? &s : NULL);
1574 if (r < 0)
1575 return r;
1576
1577 if (ret) {
94b75cdb 1578 const char *p = strstrip(s);
c56cb33f
LP
1579 if (p == s)
1580 *ret = TAKE_PTR(s);
1581 else {
94b75cdb
ZJS
1582 k = strdup_to(ret, p);
1583 if (k < 0)
1584 return k;
c56cb33f
LP
1585 }
1586 }
1587
94b75cdb 1588 return r > 0; /* Return 1 if something was read. */
c56cb33f
LP
1589}
1590
285a9b27
LP
1591int safe_fgetc(FILE *f, char *ret) {
1592 int k;
1593
1594 assert(f);
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;
1601 k = fgetc(f);
1602 if (k == EOF) {
1603 if (ferror(f))
66855de7 1604 return errno_or_else(EIO);
285a9b27
LP
1605
1606 if (ret)
1607 *ret = 0;
1608
1609 return 0;
1610 }
1611
1612 if (ret)
1613 *ret = k;
1614
1615 return 1;
1616}
7a309a8c
YW
1617
1618int warn_file_is_world_accessible(const char *filename, struct stat *st, const char *unit, unsigned line) {
1619 struct stat _st;
1620
1621 if (!filename)
1622 return 0;
1623
1624 if (!st) {
1625 if (stat(filename, &_st) < 0)
1626 return -errno;
1627 st = &_st;
1628 }
1629
1630 if ((st->st_mode & S_IRWXO) == 0)
1631 return 0;
1632
1633 if (unit)
1634 log_syntax(unit, LOG_WARNING, filename, line, 0,
0f935776 1635 "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
7a309a8c
YW
1636 filename, st->st_mode & 07777);
1637 else
0f935776 1638 log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
7a309a8c
YW
1639 filename, st->st_mode & 07777);
1640 return 0;
1641}