]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/fileio.c
fileio: fputs_with_space → _with_separator and modernization
[thirdparty/systemd.git] / src / basic / fileio.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <ctype.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <limits.h>
7 #include <stdarg.h>
8 #include <stdint.h>
9 #include <stdio_ext.h>
10 #include <stdlib.h>
11 #include <sys/stat.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14
15 #include "alloc-util.h"
16 #include "chase.h"
17 #include "fd-util.h"
18 #include "fileio.h"
19 #include "fs-util.h"
20 #include "hexdecoct.h"
21 #include "log.h"
22 #include "macro.h"
23 #include "mkdir.h"
24 #include "nulstr-util.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 #include "socket-util.h"
28 #include "stdio-util.h"
29 #include "string-util.h"
30 #include "sync-util.h"
31 #include "terminal-util.h"
32 #include "tmpfile-util.h"
33
34 /* The maximum size of the file we'll read in one go in read_full_file() (64M). */
35 #define READ_FULL_BYTES_MAX (64U*1024U*1024U - 1U)
36 /* Used when a size is specified for read_full_file() with READ_FULL_FILE_UNBASE64 or _UNHEX */
37 #define READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY 3
38
39 /* The maximum size of virtual files (i.e. procfs, sysfs, and other virtual "API" files) we'll read in one go
40 * in read_virtual_file(). Note that this limit is different (and much lower) than the READ_FULL_BYTES_MAX
41 * limit. This reflects the fact that we use different strategies for reading virtual and regular files:
42 * virtual files we generally have to read in a single read() syscall since the kernel doesn't support
43 * continuation read()s for them. Thankfully they are somewhat size constrained. Thus we can allocate the
44 * full potential buffer in advance. Regular files OTOH can be much larger, and there we grow the allocations
45 * exponentially in a loop. We use a size limit of 4M-2 because 4M-1 is the maximum buffer that /proc/sys/
46 * allows us to read() (larger reads will fail with ENOMEM), and we want to read one extra byte so that we
47 * can detect EOFs. */
48 #define READ_VIRTUAL_BYTES_MAX (4U*1024U*1024U - 2U)
49
50 int fdopen_unlocked(int fd, const char *options, FILE **ret) {
51 assert(ret);
52
53 FILE *f = fdopen(fd, options);
54 if (!f)
55 return -errno;
56
57 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
58
59 *ret = f;
60 return 0;
61 }
62
63 int take_fdopen_unlocked(int *fd, const char *options, FILE **ret) {
64 int r;
65
66 assert(fd);
67
68 r = fdopen_unlocked(*fd, options, ret);
69 if (r < 0)
70 return r;
71
72 *fd = -EBADF;
73
74 return 0;
75 }
76
77 FILE* take_fdopen(int *fd, const char *options) {
78 assert(fd);
79
80 FILE *f = fdopen(*fd, options);
81 if (!f)
82 return NULL;
83
84 *fd = -EBADF;
85
86 return f;
87 }
88
89 DIR* take_fdopendir(int *dfd) {
90 assert(dfd);
91
92 DIR *d = fdopendir(*dfd);
93 if (!d)
94 return NULL;
95
96 *dfd = -EBADF;
97
98 return d;
99 }
100
101 FILE* open_memstream_unlocked(char **ptr, size_t *sizeloc) {
102 FILE *f = open_memstream(ptr, sizeloc);
103 if (!f)
104 return NULL;
105
106 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
107
108 return f;
109 }
110
111 FILE* fmemopen_unlocked(void *buf, size_t size, const char *mode) {
112 FILE *f = fmemopen(buf, size, mode);
113 if (!f)
114 return NULL;
115
116 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
117
118 return f;
119 }
120
121 int write_string_stream_ts(
122 FILE *f,
123 const char *line,
124 WriteStringFileFlags flags,
125 const struct timespec *ts) {
126
127 bool needs_nl;
128 int r, fd = -EBADF;
129
130 assert(f);
131 assert(line);
132
133 if (ferror(f))
134 return -EIO;
135
136 if (ts) {
137 /* If we shall set the timestamp we need the fd. But fmemopen() streams generally don't have
138 * an fd. Let's fail early in that case. */
139 fd = fileno(f);
140 if (fd < 0)
141 return -EBADF;
142 }
143
144 if (flags & WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) {
145 _cleanup_free_ char *t = NULL;
146
147 /* If value to be written is same as that of the existing value, then suppress the write. */
148
149 if (fd < 0) {
150 fd = fileno(f);
151 if (fd < 0)
152 return -EBADF;
153 }
154
155 /* Read an additional byte to detect cases where the prefix matches but the rest
156 * doesn't. Also, 0 returned by read_virtual_file_fd() means the read was truncated and
157 * it won't be equal to the new value. */
158 if (read_virtual_file_fd(fd, strlen(line)+1, &t, NULL) > 0 &&
159 streq_skip_trailing_chars(line, t, NEWLINE)) {
160 log_debug("No change in value '%s', suppressing write", line);
161 return 0;
162 }
163
164 if (lseek(fd, 0, SEEK_SET) < 0)
165 return -errno;
166 }
167
168 needs_nl = !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) && !endswith(line, "\n");
169
170 if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) {
171 /* If STDIO buffering was disabled, then let's append the newline character to the string
172 * itself, so that the write goes out in one go, instead of two */
173
174 line = strjoina(line, "\n");
175 needs_nl = false;
176 }
177
178 if (fputs(line, f) == EOF)
179 return -errno;
180
181 if (needs_nl)
182 if (fputc('\n', f) == EOF)
183 return -errno;
184
185 if (flags & WRITE_STRING_FILE_SYNC)
186 r = fflush_sync_and_check(f);
187 else
188 r = fflush_and_check(f);
189 if (r < 0)
190 return r;
191
192 if (ts) {
193 const struct timespec twice[2] = {*ts, *ts};
194
195 assert(fd >= 0);
196 if (futimens(fd, twice) < 0)
197 return -errno;
198 }
199
200 return 0;
201 }
202
203 static mode_t write_string_file_flags_to_mode(WriteStringFileFlags flags) {
204
205 /* We support three different modes, that are the ones that really make sense for text files like this:
206 *
207 * → 0600 (i.e. root-only)
208 * → 0444 (i.e. read-only)
209 * → 0644 (i.e. writable for root, readable for everyone else)
210 */
211
212 return FLAGS_SET(flags, WRITE_STRING_FILE_MODE_0600) ? 0600 :
213 FLAGS_SET(flags, WRITE_STRING_FILE_MODE_0444) ? 0444 : 0644;
214 }
215
216 static int write_string_file_atomic_at(
217 int dir_fd,
218 const char *fn,
219 const char *line,
220 WriteStringFileFlags flags,
221 const struct timespec *ts) {
222
223 _cleanup_fclose_ FILE *f = NULL;
224 _cleanup_free_ char *p = NULL;
225 int r;
226
227 assert(fn);
228 assert(line);
229
230 /* Note that we'd really like to use O_TMPFILE here, but can't really, since we want replacement
231 * semantics here, and O_TMPFILE can't offer that. i.e. rename() replaces but linkat() doesn't. */
232
233 r = fopen_temporary_at(dir_fd, fn, &f, &p);
234 if (r < 0)
235 return r;
236
237 r = write_string_stream_ts(f, line, flags, ts);
238 if (r < 0)
239 goto fail;
240
241 r = fchmod_umask(fileno(f), write_string_file_flags_to_mode(flags));
242 if (r < 0)
243 goto fail;
244
245 if (renameat(dir_fd, p, dir_fd, fn) < 0) {
246 r = -errno;
247 goto fail;
248 }
249
250 if (FLAGS_SET(flags, WRITE_STRING_FILE_SYNC)) {
251 /* Sync the rename, too */
252 r = fsync_directory_of_file(fileno(f));
253 if (r < 0)
254 return r;
255 }
256
257 return 0;
258
259 fail:
260 (void) unlinkat(dir_fd, p, 0);
261 return r;
262 }
263
264 int write_string_file_ts_at(
265 int dir_fd,
266 const char *fn,
267 const char *line,
268 WriteStringFileFlags flags,
269 const struct timespec *ts) {
270
271 _cleanup_fclose_ FILE *f = NULL;
272 _cleanup_close_ int fd = -EBADF;
273 int q, r;
274
275 assert(fn);
276 assert(line);
277
278 /* We don't know how to verify whether the file contents was already on-disk. */
279 assert(!((flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE) && (flags & WRITE_STRING_FILE_SYNC)));
280
281 if (flags & WRITE_STRING_FILE_MKDIR_0755) {
282 r = mkdirat_parents(dir_fd, fn, 0755);
283 if (r < 0)
284 return r;
285 }
286
287 if (flags & WRITE_STRING_FILE_ATOMIC) {
288 assert(flags & WRITE_STRING_FILE_CREATE);
289
290 r = write_string_file_atomic_at(dir_fd, fn, line, flags, ts);
291 if (r < 0)
292 goto fail;
293
294 return r;
295 } else
296 assert(!ts);
297
298 /* We manually build our own version of fopen(..., "we") that works without O_CREAT and with O_NOFOLLOW if needed. */
299 fd = openat(dir_fd, fn, O_CLOEXEC|O_NOCTTY |
300 (FLAGS_SET(flags, WRITE_STRING_FILE_NOFOLLOW) ? O_NOFOLLOW : 0) |
301 (FLAGS_SET(flags, WRITE_STRING_FILE_CREATE) ? O_CREAT : 0) |
302 (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
303 (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY),
304 write_string_file_flags_to_mode(flags));
305 if (fd < 0) {
306 r = -errno;
307 goto fail;
308 }
309
310 r = take_fdopen_unlocked(&fd, "w", &f);
311 if (r < 0)
312 goto fail;
313
314 if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
315 setvbuf(f, NULL, _IONBF, 0);
316
317 r = write_string_stream_ts(f, line, flags, ts);
318 if (r < 0)
319 goto fail;
320
321 return 0;
322
323 fail:
324 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
325 return r;
326
327 f = safe_fclose(f);
328
329 /* OK, the operation failed, but let's see if the right
330 * contents in place already. If so, eat up the error. */
331
332 q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) || (flags & WRITE_STRING_FILE_VERIFY_IGNORE_NEWLINE));
333 if (q <= 0)
334 return r;
335
336 return 0;
337 }
338
339 int write_string_filef(
340 const char *fn,
341 WriteStringFileFlags flags,
342 const char *format, ...) {
343
344 _cleanup_free_ char *p = NULL;
345 va_list ap;
346 int r;
347
348 va_start(ap, format);
349 r = vasprintf(&p, format, ap);
350 va_end(ap);
351
352 if (r < 0)
353 return -ENOMEM;
354
355 return write_string_file(fn, p, flags);
356 }
357
358 int read_one_line_file_at(int dir_fd, const char *filename, char **ret) {
359 _cleanup_fclose_ FILE *f = NULL;
360 int r;
361
362 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
363 assert(filename);
364 assert(ret);
365
366 r = fopen_unlocked_at(dir_fd, filename, "re", 0, &f);
367 if (r < 0)
368 return r;
369
370 return read_line(f, LONG_LINE_MAX, ret);
371 }
372
373 int verify_file_at(int dir_fd, const char *fn, const char *blob, bool accept_extra_nl) {
374 _cleanup_fclose_ FILE *f = NULL;
375 _cleanup_free_ char *buf = NULL;
376 size_t l, k;
377 int r;
378
379 assert(fn);
380 assert(blob);
381
382 l = strlen(blob);
383
384 if (accept_extra_nl && endswith(blob, "\n"))
385 accept_extra_nl = false;
386
387 buf = malloc(l + accept_extra_nl + 1);
388 if (!buf)
389 return -ENOMEM;
390
391 r = fopen_unlocked_at(dir_fd, fn, "re", 0, &f);
392 if (r < 0)
393 return r;
394
395 /* We try to read one byte more than we need, so that we know whether we hit eof */
396 errno = 0;
397 k = fread(buf, 1, l + accept_extra_nl + 1, f);
398 if (ferror(f))
399 return errno_or_else(EIO);
400
401 if (k != l && k != l + accept_extra_nl)
402 return 0;
403 if (memcmp(buf, blob, l) != 0)
404 return 0;
405 if (k > l && buf[l] != '\n')
406 return 0;
407
408 return 1;
409 }
410
411 int read_virtual_file_fd(int fd, size_t max_size, char **ret_contents, size_t *ret_size) {
412 _cleanup_free_ char *buf = NULL;
413 size_t n, size;
414 int n_retries;
415 bool truncated = false;
416
417 /* Virtual filesystems such as sysfs or procfs use kernfs, and kernfs can work with two sorts of
418 * virtual files. One sort uses "seq_file", and the results of the first read are buffered for the
419 * second read. The other sort uses "raw" reads which always go direct to the device. In the latter
420 * case, the content of the virtual file must be retrieved with a single read otherwise a second read
421 * might get the new value instead of finding EOF immediately. That's the reason why the usage of
422 * fread(3) is prohibited in this case as it always performs a second call to read(2) looking for
423 * EOF. See issue #13585.
424 *
425 * max_size specifies a limit on the bytes read. If max_size is SIZE_MAX, the full file is read. If
426 * the full file is too large to read, an error is returned. For other values of max_size, *partial
427 * contents* may be returned. (Though the read is still done using one syscall.) Returns 0 on
428 * partial success, 1 if untruncated contents were read. */
429
430 assert(fd >= 0);
431 assert(max_size <= READ_VIRTUAL_BYTES_MAX || max_size == SIZE_MAX);
432
433 /* Limit the number of attempts to read the number of bytes returned by fstat(). */
434 n_retries = 3;
435
436 for (;;) {
437 struct stat st;
438
439 if (fstat(fd, &st) < 0)
440 return -errno;
441
442 if (!S_ISREG(st.st_mode))
443 return -EBADF;
444
445 /* Be prepared for files from /proc which generally report a file size of 0. */
446 assert_cc(READ_VIRTUAL_BYTES_MAX < SSIZE_MAX);
447 if (st.st_size > 0 && n_retries > 1) {
448 /* Let's use the file size if we have more than 1 attempt left. On the last attempt
449 * we'll ignore the file size */
450
451 if (st.st_size > SSIZE_MAX) { /* Avoid overflow with 32-bit size_t and 64-bit off_t. */
452
453 if (max_size == SIZE_MAX)
454 return -EFBIG;
455
456 size = max_size;
457 } else {
458 size = MIN((size_t) st.st_size, max_size);
459
460 if (size > READ_VIRTUAL_BYTES_MAX)
461 return -EFBIG;
462 }
463
464 n_retries--;
465 } else if (n_retries > 1) {
466 /* Files in /proc are generally smaller than the page size so let's start with
467 * a page size buffer from malloc and only use the max buffer on the final try. */
468 size = MIN3(page_size() - 1, READ_VIRTUAL_BYTES_MAX, max_size);
469 n_retries = 1;
470 } else {
471 size = MIN(READ_VIRTUAL_BYTES_MAX, max_size);
472 n_retries = 0;
473 }
474
475 buf = malloc(size + 1);
476 if (!buf)
477 return -ENOMEM;
478
479 /* Use a bigger allocation if we got it anyway, but not more than the limit. */
480 size = MIN3(MALLOC_SIZEOF_SAFE(buf) - 1, max_size, READ_VIRTUAL_BYTES_MAX);
481
482 for (;;) {
483 ssize_t k;
484
485 /* Read one more byte so we can detect whether the content of the
486 * file has already changed or the guessed size for files from /proc
487 * wasn't large enough . */
488 k = read(fd, buf, size + 1);
489 if (k >= 0) {
490 n = k;
491 break;
492 }
493
494 if (errno != EINTR)
495 return -errno;
496 }
497
498 /* Consider a short read as EOF */
499 if (n <= size)
500 break;
501
502 /* If a maximum size is specified and we already read more we know the file is larger, and
503 * can handle this as truncation case. Note that if the size of what we read equals the
504 * maximum size then this doesn't mean truncation, the file might or might not end on that
505 * byte. We need to rerun the loop in that case, with a larger buffer size, so that we read
506 * at least one more byte to be able to distinguish EOF from truncation. */
507 if (max_size != SIZE_MAX && n > max_size) {
508 n = size; /* Make sure we never use more than what we sized the buffer for (so that
509 * we have one free byte in it for the trailing NUL we add below). */
510 truncated = true;
511 break;
512 }
513
514 /* We have no further attempts left? Then the file is apparently larger than our limits. Give up. */
515 if (n_retries <= 0)
516 return -EFBIG;
517
518 /* Hmm... either we read too few bytes from /proc or less likely the content of the file
519 * might have been changed (and is now bigger) while we were processing, let's try again
520 * either with the new file size. */
521
522 if (lseek(fd, 0, SEEK_SET) < 0)
523 return -errno;
524
525 buf = mfree(buf);
526 }
527
528 if (ret_contents) {
529
530 /* Safety check: if the caller doesn't want to know the size of what we just read it will
531 * rely on the trailing NUL byte. But if there's an embedded NUL byte, then we should refuse
532 * operation as otherwise there'd be ambiguity about what we just read. */
533 if (!ret_size && memchr(buf, 0, n))
534 return -EBADMSG;
535
536 if (n < size) {
537 char *p;
538
539 /* Return rest of the buffer to libc */
540 p = realloc(buf, n + 1);
541 if (!p)
542 return -ENOMEM;
543 buf = p;
544 }
545
546 buf[n] = 0;
547 *ret_contents = TAKE_PTR(buf);
548 }
549
550 if (ret_size)
551 *ret_size = n;
552
553 return !truncated;
554 }
555
556 int read_virtual_file_at(
557 int dir_fd,
558 const char *filename,
559 size_t max_size,
560 char **ret_contents,
561 size_t *ret_size) {
562
563 _cleanup_close_ int fd = -EBADF;
564
565 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
566
567 if (!filename) {
568 if (dir_fd == AT_FDCWD)
569 return -EBADF;
570
571 return read_virtual_file_fd(dir_fd, max_size, ret_contents, ret_size);
572 }
573
574 fd = openat(dir_fd, filename, O_RDONLY | O_NOCTTY | O_CLOEXEC);
575 if (fd < 0)
576 return -errno;
577
578 return read_virtual_file_fd(fd, max_size, ret_contents, ret_size);
579 }
580
581 int read_full_stream_full(
582 FILE *f,
583 const char *filename,
584 uint64_t offset,
585 size_t size,
586 ReadFullFileFlags flags,
587 char **ret_contents,
588 size_t *ret_size) {
589
590 _cleanup_free_ char *buf = NULL;
591 size_t n, n_next = 0, l, expected_decoded_size = size;
592 int fd, r;
593
594 assert(f);
595 assert(ret_contents);
596 assert(!FLAGS_SET(flags, READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX));
597 assert(size != SIZE_MAX || !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER));
598
599 if (offset != UINT64_MAX && offset > LONG_MAX) /* fseek() can only deal with "long" offsets */
600 return -ERANGE;
601
602 if ((flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) != 0) {
603 if (size <= SIZE_MAX / READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY)
604 size *= READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY;
605 else
606 size = SIZE_MAX;
607 }
608
609 fd = fileno(f);
610 if (fd >= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see
611 * fmemopen()), let's optimize our buffering */
612 struct stat st;
613
614 if (fstat(fd, &st) < 0)
615 return -errno;
616
617 if (S_ISREG(st.st_mode)) {
618
619 /* Try to start with the right file size if we shall read the file in full. Note
620 * that we increase the size to read here by one, so that the first read attempt
621 * already makes us notice the EOF. If the reported size of the file is zero, we
622 * avoid this logic however, since quite likely it might be a virtual file in procfs
623 * that all report a zero file size. */
624
625 if (st.st_size > 0 &&
626 (size == SIZE_MAX || FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER))) {
627
628 uint64_t rsize =
629 LESS_BY((uint64_t) st.st_size, offset == UINT64_MAX ? 0 : offset);
630
631 if (rsize < SIZE_MAX) /* overflow check */
632 n_next = rsize + 1;
633 }
634
635 if (flags & READ_FULL_FILE_WARN_WORLD_READABLE)
636 (void) warn_file_is_world_accessible(filename, &st, NULL, 0);
637 }
638 }
639
640 /* If we don't know how much to read, figure it out now. If we shall read a part of the file, then
641 * allocate the requested size. If we shall load the full file start with LINE_MAX. Note that if
642 * READ_FULL_FILE_FAIL_WHEN_LARGER we consider the specified size a safety limit, and thus also start
643 * with LINE_MAX, under assumption the file is most likely much shorter. */
644 if (n_next == 0)
645 n_next = size != SIZE_MAX && !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) ? size : LINE_MAX;
646
647 /* Never read more than we need to determine that our own limit is hit */
648 if (n_next > READ_FULL_BYTES_MAX)
649 n_next = READ_FULL_BYTES_MAX + 1;
650
651 if (offset != UINT64_MAX && fseek(f, offset, SEEK_SET) < 0)
652 return -errno;
653
654 n = l = 0;
655 for (;;) {
656 char *t;
657 size_t k;
658
659 /* If we shall fail when reading overly large data, then read exactly one byte more than the
660 * specified size at max, since that'll tell us if there's anymore data beyond the limit*/
661 if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && n_next > size)
662 n_next = size + 1;
663
664 if (flags & READ_FULL_FILE_SECURE) {
665 t = malloc(n_next + 1);
666 if (!t) {
667 r = -ENOMEM;
668 goto finalize;
669 }
670 memcpy_safe(t, buf, n);
671 explicit_bzero_safe(buf, n);
672 free(buf);
673 } else {
674 t = realloc(buf, n_next + 1);
675 if (!t)
676 return -ENOMEM;
677 }
678
679 buf = t;
680 /* Unless a size has been explicitly specified, try to read as much as fits into the memory
681 * we allocated (minus 1, to leave one byte for the safety NUL byte) */
682 n = size == SIZE_MAX ? MALLOC_SIZEOF_SAFE(buf) - 1 : n_next;
683
684 errno = 0;
685 k = fread(buf + l, 1, n - l, f);
686
687 assert(k <= n - l);
688 l += k;
689
690 if (ferror(f)) {
691 r = errno_or_else(EIO);
692 goto finalize;
693 }
694 if (feof(f))
695 break;
696
697 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 */
698 assert(l == size);
699 break;
700 }
701
702 assert(k > 0); /* we can't have read zero bytes because that would have been EOF */
703
704 if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && l > size) {
705 r = -E2BIG;
706 goto finalize;
707 }
708
709 if (n >= READ_FULL_BYTES_MAX) {
710 r = -E2BIG;
711 goto finalize;
712 }
713
714 n_next = MIN(n * 2, READ_FULL_BYTES_MAX);
715 }
716
717 if (flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) {
718 _cleanup_free_ void *decoded = NULL;
719 size_t decoded_size;
720
721 buf[l++] = 0;
722 if (flags & READ_FULL_FILE_UNBASE64)
723 r = unbase64mem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size);
724 else
725 r = unhexmem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size);
726 if (r < 0)
727 goto finalize;
728
729 if (flags & READ_FULL_FILE_SECURE)
730 explicit_bzero_safe(buf, n);
731 free_and_replace(buf, decoded);
732 n = l = decoded_size;
733
734 if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && l > expected_decoded_size) {
735 r = -E2BIG;
736 goto finalize;
737 }
738 }
739
740 if (!ret_size) {
741 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
742 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
743 * there'd be ambiguity about what we just read. */
744
745 if (memchr(buf, 0, l)) {
746 r = -EBADMSG;
747 goto finalize;
748 }
749 }
750
751 buf[l] = 0;
752 *ret_contents = TAKE_PTR(buf);
753
754 if (ret_size)
755 *ret_size = l;
756
757 return 0;
758
759 finalize:
760 if (flags & READ_FULL_FILE_SECURE)
761 explicit_bzero_safe(buf, n);
762
763 return r;
764 }
765
766 int read_full_file_full(
767 int dir_fd,
768 const char *filename,
769 uint64_t offset,
770 size_t size,
771 ReadFullFileFlags flags,
772 const char *bind_name,
773 char **ret_contents,
774 size_t *ret_size) {
775
776 _cleanup_fclose_ FILE *f = NULL;
777 XfopenFlags xflags = XFOPEN_UNLOCKED;
778 int r;
779
780 assert(filename);
781 assert(ret_contents);
782
783 if (FLAGS_SET(flags, READ_FULL_FILE_CONNECT_SOCKET) && /* If this is enabled, let's try to connect to it */
784 offset == UINT64_MAX) /* Seeking is not supported on AF_UNIX sockets */
785 xflags |= XFOPEN_SOCKET;
786
787 r = xfopenat_full(dir_fd, filename, "re", 0, xflags, bind_name, &f);
788 if (r < 0)
789 return r;
790
791 return read_full_stream_full(f, filename, offset, size, flags, ret_contents, ret_size);
792 }
793
794 int executable_is_script(const char *path, char **interpreter) {
795 _cleanup_free_ char *line = NULL;
796 size_t len;
797 char *ans;
798 int r;
799
800 assert(path);
801
802 r = read_one_line_file(path, &line);
803 if (r == -ENOBUFS) /* First line overly long? if so, then it's not a script */
804 return 0;
805 if (r < 0)
806 return r;
807
808 if (!startswith(line, "#!"))
809 return 0;
810
811 ans = strstrip(line + 2);
812 len = strcspn(ans, " \t");
813
814 if (len == 0)
815 return 0;
816
817 ans = strndup(ans, len);
818 if (!ans)
819 return -ENOMEM;
820
821 *interpreter = ans;
822 return 1;
823 }
824
825 /**
826 * Retrieve one field from a file like /proc/self/status. pattern
827 * should not include whitespace or the delimiter (':'). pattern matches only
828 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
829 * zeros after the ':' will be skipped. field must be freed afterwards.
830 * terminator specifies the terminating characters of the field value (not
831 * included in the value).
832 */
833 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
834 _cleanup_free_ char *status = NULL;
835 char *t, *f;
836 int r;
837
838 assert(terminator);
839 assert(filename);
840 assert(pattern);
841 assert(field);
842
843 r = read_full_virtual_file(filename, &status, NULL);
844 if (r < 0)
845 return r;
846
847 t = status;
848
849 do {
850 bool pattern_ok;
851
852 do {
853 t = strstr(t, pattern);
854 if (!t)
855 return -ENOENT;
856
857 /* Check that pattern occurs in beginning of line. */
858 pattern_ok = (t == status || t[-1] == '\n');
859
860 t += strlen(pattern);
861
862 } while (!pattern_ok);
863
864 t += strspn(t, " \t");
865 if (!*t)
866 return -ENOENT;
867
868 } while (*t != ':');
869
870 t++;
871
872 if (*t) {
873 t += strspn(t, " \t");
874
875 /* Also skip zeros, because when this is used for
876 * capabilities, we don't want the zeros. This way the
877 * same capability set always maps to the same string,
878 * irrespective of the total capability set size. For
879 * other numbers it shouldn't matter. */
880 t += strspn(t, "0");
881 /* Back off one char if there's nothing but whitespace
882 and zeros */
883 if (!*t || isspace(*t))
884 t--;
885 }
886
887 f = strdupcspn(t, terminator);
888 if (!f)
889 return -ENOMEM;
890
891 *field = f;
892 return 0;
893 }
894
895 DIR *xopendirat(int fd, const char *name, int flags) {
896 _cleanup_close_ int nfd = -EBADF;
897
898 assert(!(flags & O_CREAT));
899
900 if (fd == AT_FDCWD && flags == 0)
901 return opendir(name);
902
903 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
904 if (nfd < 0)
905 return NULL;
906
907 return take_fdopendir(&nfd);
908 }
909
910 int fopen_mode_to_flags(const char *mode) {
911 const char *p;
912 int flags;
913
914 assert(mode);
915
916 if ((p = startswith(mode, "r+")))
917 flags = O_RDWR;
918 else if ((p = startswith(mode, "r")))
919 flags = O_RDONLY;
920 else if ((p = startswith(mode, "w+")))
921 flags = O_RDWR|O_CREAT|O_TRUNC;
922 else if ((p = startswith(mode, "w")))
923 flags = O_WRONLY|O_CREAT|O_TRUNC;
924 else if ((p = startswith(mode, "a+")))
925 flags = O_RDWR|O_CREAT|O_APPEND;
926 else if ((p = startswith(mode, "a")))
927 flags = O_WRONLY|O_CREAT|O_APPEND;
928 else
929 return -EINVAL;
930
931 for (; *p != 0; p++) {
932
933 switch (*p) {
934
935 case 'e':
936 flags |= O_CLOEXEC;
937 break;
938
939 case 'x':
940 flags |= O_EXCL;
941 break;
942
943 case 'm':
944 /* ignore this here, fdopen() might care later though */
945 break;
946
947 case 'c': /* not sure what to do about this one */
948 default:
949 return -EINVAL;
950 }
951 }
952
953 return flags;
954 }
955
956 static int xfopenat_regular(int dir_fd, const char *path, const char *mode, int open_flags, FILE **ret) {
957 FILE *f;
958
959 /* A combination of fopen() with openat() */
960
961 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
962 assert(path);
963 assert(mode);
964 assert(ret);
965
966 if (dir_fd == AT_FDCWD && open_flags == 0)
967 f = fopen(path, mode);
968 else {
969 _cleanup_close_ int fd = -EBADF;
970 int mode_flags;
971
972 mode_flags = fopen_mode_to_flags(mode);
973 if (mode_flags < 0)
974 return mode_flags;
975
976 fd = openat(dir_fd, path, mode_flags | open_flags);
977 if (fd < 0)
978 return -errno;
979
980 f = take_fdopen(&fd, mode);
981 }
982 if (!f)
983 return -errno;
984
985 *ret = f;
986 return 0;
987 }
988
989 static int xfopenat_unix_socket(int dir_fd, const char *path, const char *bind_name, FILE **ret) {
990 _cleanup_close_ int sk = -EBADF;
991 FILE *f;
992 int r;
993
994 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
995 assert(path);
996 assert(ret);
997
998 sk = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
999 if (sk < 0)
1000 return -errno;
1001
1002 if (bind_name) {
1003 /* If the caller specified a socket name to bind to, do so before connecting. This is
1004 * useful to communicate some minor, short meta-information token from the client to
1005 * the server. */
1006 union sockaddr_union bsa;
1007
1008 r = sockaddr_un_set_path(&bsa.un, bind_name);
1009 if (r < 0)
1010 return r;
1011
1012 if (bind(sk, &bsa.sa, r) < 0)
1013 return -errno;
1014 }
1015
1016 r = connect_unix_path(sk, dir_fd, path);
1017 if (r < 0)
1018 return r;
1019
1020 if (shutdown(sk, SHUT_WR) < 0)
1021 return -errno;
1022
1023 f = take_fdopen(&sk, "r");
1024 if (!f)
1025 return -errno;
1026
1027 *ret = f;
1028 return 0;
1029 }
1030
1031 int xfopenat_full(
1032 int dir_fd,
1033 const char *path,
1034 const char *mode,
1035 int open_flags,
1036 XfopenFlags flags,
1037 const char *bind_name,
1038 FILE **ret) {
1039
1040 FILE *f = NULL; /* avoid false maybe-uninitialized warning */
1041 int r;
1042
1043 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1044 assert(path);
1045 assert(mode);
1046 assert(ret);
1047
1048 r = xfopenat_regular(dir_fd, path, mode, open_flags, &f);
1049 if (r == -ENXIO && FLAGS_SET(flags, XFOPEN_SOCKET)) {
1050 /* ENXIO is what Linux returns if we open a node that is an AF_UNIX socket */
1051 r = xfopenat_unix_socket(dir_fd, path, bind_name, &f);
1052 if (IN_SET(r, -ENOTSOCK, -EINVAL))
1053 return -ENXIO; /* propagate original error if this is not a socket after all */
1054 }
1055 if (r < 0)
1056 return r;
1057
1058 if (FLAGS_SET(flags, XFOPEN_UNLOCKED))
1059 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
1060
1061 *ret = f;
1062 return 0;
1063 }
1064
1065 int fdopen_independent(int fd, const char *mode, FILE **ret) {
1066 _cleanup_close_ int copy_fd = -EBADF;
1067 _cleanup_fclose_ FILE *f = NULL;
1068 int mode_flags;
1069
1070 assert(fd >= 0);
1071 assert(mode);
1072 assert(ret);
1073
1074 /* A combination of fdopen() + fd_reopen(). i.e. reopens the inode the specified fd points to and
1075 * returns a FILE* for it */
1076
1077 mode_flags = fopen_mode_to_flags(mode);
1078 if (mode_flags < 0)
1079 return mode_flags;
1080
1081 /* Flags returned by fopen_mode_to_flags might contain O_CREAT, but it doesn't make sense for fd_reopen
1082 * since we're working on an existing fd anyway. Let's drop it here to avoid triggering assertion. */
1083 copy_fd = fd_reopen(fd, mode_flags & ~O_CREAT);
1084 if (copy_fd < 0)
1085 return copy_fd;
1086
1087 f = take_fdopen(&copy_fd, mode);
1088 if (!f)
1089 return -errno;
1090
1091 *ret = TAKE_PTR(f);
1092 return 0;
1093 }
1094
1095 static int search_and_open_internal(
1096 const char *path,
1097 int mode, /* if ret_fd is NULL this is an [FRWX]_OK mode for access(), otherwise an open mode for open() */
1098 const char *root,
1099 char **search,
1100 int *ret_fd,
1101 char **ret_path) {
1102
1103 int r;
1104
1105 assert(!ret_fd || !FLAGS_SET(mode, O_CREAT)); /* We don't support O_CREAT for this */
1106 assert(path);
1107
1108 if (path_is_absolute(path)) {
1109 _cleanup_close_ int fd = -EBADF;
1110
1111 if (ret_fd)
1112 /* We only specify 0777 here to appease static analyzers, it's never used since we
1113 * don't support O_CREAT here */
1114 r = fd = RET_NERRNO(open(path, mode, 0777));
1115 else
1116 r = RET_NERRNO(access(path, mode));
1117 if (r < 0)
1118 return r;
1119
1120 if (ret_path) {
1121 r = path_simplify_alloc(path, ret_path);
1122 if (r < 0)
1123 return r;
1124 }
1125
1126 if (ret_fd)
1127 *ret_fd = TAKE_FD(fd);
1128
1129 return 0;
1130 }
1131
1132 if (!path_strv_resolve_uniq(search, root))
1133 return -ENOMEM;
1134
1135 STRV_FOREACH(i, search) {
1136 _cleanup_close_ int fd = -EBADF;
1137 _cleanup_free_ char *p = NULL;
1138
1139 p = path_join(root, *i, path);
1140 if (!p)
1141 return -ENOMEM;
1142
1143 if (ret_fd)
1144 /* as above, 0777 is static analyzer appeasement */
1145 r = fd = RET_NERRNO(open(p, mode, 0777));
1146 else
1147 r = RET_NERRNO(access(p, F_OK));
1148 if (r >= 0) {
1149 if (ret_path)
1150 *ret_path = path_simplify(TAKE_PTR(p));
1151
1152 if (ret_fd)
1153 *ret_fd = TAKE_FD(fd);
1154
1155 return 0;
1156 }
1157 if (r != -ENOENT)
1158 return r;
1159 }
1160
1161 return -ENOENT;
1162 }
1163
1164 int search_and_open(
1165 const char *path,
1166 int mode,
1167 const char *root,
1168 char **search,
1169 int *ret_fd,
1170 char **ret_path) {
1171
1172 _cleanup_strv_free_ char **copy = NULL;
1173
1174 assert(path);
1175
1176 copy = strv_copy((char**) search);
1177 if (!copy)
1178 return -ENOMEM;
1179
1180 return search_and_open_internal(path, mode, root, copy, ret_fd, ret_path);
1181 }
1182
1183 static int search_and_fopen_internal(
1184 const char *path,
1185 const char *mode,
1186 const char *root,
1187 char **search,
1188 FILE **ret_file,
1189 char **ret_path) {
1190
1191 _cleanup_free_ char *found_path = NULL;
1192 _cleanup_close_ int fd = -EBADF;
1193 int r;
1194
1195 assert(path);
1196 assert(mode || !ret_file);
1197
1198 r = search_and_open(
1199 path,
1200 mode ? fopen_mode_to_flags(mode) : 0,
1201 root,
1202 search,
1203 ret_file ? &fd : NULL,
1204 ret_path ? &found_path : NULL);
1205 if (r < 0)
1206 return r;
1207
1208 if (ret_file) {
1209 FILE *f = take_fdopen(&fd, mode);
1210 if (!f)
1211 return -errno;
1212
1213 *ret_file = f;
1214 }
1215
1216 if (ret_path)
1217 *ret_path = TAKE_PTR(found_path);
1218
1219 return 0;
1220 }
1221
1222 int search_and_fopen(
1223 const char *path,
1224 const char *mode,
1225 const char *root,
1226 const char **search,
1227 FILE **ret_file,
1228 char **ret_path) {
1229
1230 _cleanup_strv_free_ char **copy = NULL;
1231
1232 assert(path);
1233 assert(mode || !ret_file);
1234
1235 copy = strv_copy((char**) search);
1236 if (!copy)
1237 return -ENOMEM;
1238
1239 return search_and_fopen_internal(path, mode, root, copy, ret_file, ret_path);
1240 }
1241
1242 int search_and_fopen_nulstr(
1243 const char *path,
1244 const char *mode,
1245 const char *root,
1246 const char *search,
1247 FILE **ret_file,
1248 char **ret_path) {
1249
1250 _cleanup_strv_free_ char **l = NULL;
1251
1252 assert(path);
1253 assert(mode || !ret_file);
1254
1255 l = strv_split_nulstr(search);
1256 if (!l)
1257 return -ENOMEM;
1258
1259 return search_and_fopen_internal(path, mode, root, l, ret_file, ret_path);
1260 }
1261
1262 int fflush_and_check(FILE *f) {
1263 assert(f);
1264
1265 errno = 0;
1266 fflush(f);
1267
1268 if (ferror(f))
1269 return errno_or_else(EIO);
1270
1271 return 0;
1272 }
1273
1274 int fflush_sync_and_check(FILE *f) {
1275 int r, fd;
1276
1277 assert(f);
1278
1279 r = fflush_and_check(f);
1280 if (r < 0)
1281 return r;
1282
1283 /* Not all file streams have an fd associated (think: fmemopen()), let's handle this gracefully and
1284 * assume that in that case we need no explicit syncing */
1285 fd = fileno(f);
1286 if (fd < 0)
1287 return 0;
1288
1289 r = fsync_full(fd);
1290 if (r < 0)
1291 return r;
1292
1293 return 0;
1294 }
1295
1296 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1297 char ln[DECIMAL_STR_MAX(n)+2];
1298
1299 /* Creates a "timestamp" file, that contains nothing but a
1300 * usec_t timestamp, formatted in ASCII. */
1301
1302 if (!timestamp_is_set(n))
1303 return -ERANGE;
1304
1305 xsprintf(ln, USEC_FMT "\n", n);
1306
1307 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1308 }
1309
1310 int read_timestamp_file(const char *fn, usec_t *ret) {
1311 _cleanup_free_ char *ln = NULL;
1312 uint64_t t;
1313 int r;
1314
1315 r = read_one_line_file(fn, &ln);
1316 if (r < 0)
1317 return r;
1318
1319 r = safe_atou64(ln, &t);
1320 if (r < 0)
1321 return r;
1322
1323 if (!timestamp_is_set(t))
1324 return -ERANGE;
1325
1326 *ret = (usec_t) t;
1327 return 0;
1328 }
1329
1330 int fputs_with_separator(FILE *f, const char *s, const char *separator, bool *space) {
1331 assert(s);
1332 assert(space);
1333
1334 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator.
1335 * The *space parameter when specified shall initially point to a boolean variable initialized
1336 * to false. It is set to true after the first invocation. This call is supposed to be use in loops,
1337 * where a separator shall be inserted between each element, but not before the first one. */
1338
1339 if (!f)
1340 f = stdout;
1341
1342 if (!separator)
1343 separator = " ";
1344
1345 if (*space)
1346 if (fputs(separator, f) < 0)
1347 return -EIO;
1348
1349 *space = true;
1350
1351 if (fputs(s, f) < 0)
1352 return -EIO;
1353
1354 return 0;
1355 }
1356
1357 /* A bitmask of the EOL markers we know */
1358 typedef enum EndOfLineMarker {
1359 EOL_NONE = 0,
1360 EOL_ZERO = 1 << 0, /* \0 (aka NUL) */
1361 EOL_TEN = 1 << 1, /* \n (aka NL, aka LF) */
1362 EOL_THIRTEEN = 1 << 2, /* \r (aka CR) */
1363 } EndOfLineMarker;
1364
1365 static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) {
1366
1367 if (!FLAGS_SET(flags, READ_LINE_ONLY_NUL)) {
1368 if (c == '\n')
1369 return EOL_TEN;
1370 if (c == '\r')
1371 return EOL_THIRTEEN;
1372 }
1373
1374 if (c == '\0')
1375 return EOL_ZERO;
1376
1377 return EOL_NONE;
1378 }
1379
1380 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile, NULL);
1381
1382 int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) {
1383 _cleanup_free_ char *buffer = NULL;
1384 size_t n = 0, count = 0;
1385 int r;
1386
1387 assert(f);
1388
1389 /* Something like a bounded version of getline().
1390 *
1391 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
1392 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
1393 * endings:
1394 *
1395 * • \n (UNIX)
1396 * • \r (old MacOS)
1397 * • \0 (C strings)
1398 * • \n\0
1399 * • \r\0
1400 * • \r\n (Windows)
1401 * • \n\r
1402 * • \r\n\0
1403 * • \n\r\0
1404 *
1405 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1406 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1407 *
1408 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1409 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1410 *
1411 * If a line shall be skipped ret may be initialized as NULL. */
1412
1413 if (ret) {
1414 if (!GREEDY_REALLOC(buffer, 1))
1415 return -ENOMEM;
1416 }
1417
1418 {
1419 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
1420 EndOfLineMarker previous_eol = EOL_NONE;
1421 flockfile(f);
1422
1423 for (;;) {
1424 EndOfLineMarker eol;
1425 char c;
1426
1427 if (n >= limit)
1428 return -ENOBUFS;
1429
1430 if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */
1431 return -ENOBUFS;
1432
1433 r = safe_fgetc(f, &c);
1434 if (r < 0)
1435 return r;
1436 if (r == 0) /* EOF is definitely EOL */
1437 break;
1438
1439 eol = categorize_eol(c, flags);
1440
1441 if (FLAGS_SET(previous_eol, EOL_ZERO) ||
1442 (eol == EOL_NONE && previous_eol != EOL_NONE) ||
1443 (eol != EOL_NONE && (previous_eol & eol) != 0)) {
1444 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
1445 * EOL marker has been seen right before? In either of these three cases we are
1446 * done. But first, let's put this character back in the queue. (Note that we have to
1447 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
1448 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
1449 * pass a negative value here. That said, to complicate things further ungetc() is
1450 * actually happy with most negative characters and implicitly casts them back to
1451 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
1452 * godawful API!) */
1453 assert_se(ungetc((unsigned char) c, f) != EOF);
1454 break;
1455 }
1456
1457 count++;
1458
1459 if (eol != EOL_NONE) {
1460 /* If we are on a tty, we can't shouldn't wait for more input, because that
1461 * generally means waiting for the user, interactively. In the case of a TTY
1462 * we expect only \n as the single EOL marker, so we are in the lucky
1463 * position that there is no need to wait. We check this condition last, to
1464 * avoid isatty() check if not necessary. */
1465
1466 if ((flags & (READ_LINE_IS_A_TTY|READ_LINE_NOT_A_TTY)) == 0) {
1467 int fd;
1468
1469 fd = fileno(f);
1470 if (fd < 0) /* Maybe an fmemopen() stream? Handle this gracefully,
1471 * and don't call isatty() on an invalid fd */
1472 flags |= READ_LINE_NOT_A_TTY;
1473 else
1474 flags |= isatty_safe(fd) ? READ_LINE_IS_A_TTY : READ_LINE_NOT_A_TTY;
1475 }
1476 if (FLAGS_SET(flags, READ_LINE_IS_A_TTY))
1477 break;
1478 }
1479
1480 if (eol != EOL_NONE) {
1481 previous_eol |= eol;
1482 continue;
1483 }
1484
1485 if (ret) {
1486 if (!GREEDY_REALLOC(buffer, n + 2))
1487 return -ENOMEM;
1488
1489 buffer[n] = c;
1490 }
1491
1492 n++;
1493 }
1494 }
1495
1496 if (ret) {
1497 buffer[n] = 0;
1498
1499 *ret = TAKE_PTR(buffer);
1500 }
1501
1502 return (int) count;
1503 }
1504
1505 int read_stripped_line(FILE *f, size_t limit, char **ret) {
1506 _cleanup_free_ char *s = NULL;
1507 int r;
1508
1509 assert(f);
1510
1511 r = read_line(f, limit, ret ? &s : NULL);
1512 if (r < 0)
1513 return r;
1514
1515 if (ret) {
1516 const char *p;
1517
1518 p = strstrip(s);
1519 if (p == s)
1520 *ret = TAKE_PTR(s);
1521 else {
1522 char *copy;
1523
1524 copy = strdup(p);
1525 if (!copy)
1526 return -ENOMEM;
1527
1528 *ret = copy;
1529 }
1530 }
1531
1532 return r;
1533 }
1534
1535 int safe_fgetc(FILE *f, char *ret) {
1536 int k;
1537
1538 assert(f);
1539
1540 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
1541 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
1542 * has. */
1543
1544 errno = 0;
1545 k = fgetc(f);
1546 if (k == EOF) {
1547 if (ferror(f))
1548 return errno_or_else(EIO);
1549
1550 if (ret)
1551 *ret = 0;
1552
1553 return 0;
1554 }
1555
1556 if (ret)
1557 *ret = k;
1558
1559 return 1;
1560 }
1561
1562 int warn_file_is_world_accessible(const char *filename, struct stat *st, const char *unit, unsigned line) {
1563 struct stat _st;
1564
1565 if (!filename)
1566 return 0;
1567
1568 if (!st) {
1569 if (stat(filename, &_st) < 0)
1570 return -errno;
1571 st = &_st;
1572 }
1573
1574 if ((st->st_mode & S_IRWXO) == 0)
1575 return 0;
1576
1577 if (unit)
1578 log_syntax(unit, LOG_WARNING, filename, line, 0,
1579 "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1580 filename, st->st_mode & 07777);
1581 else
1582 log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1583 filename, st->st_mode & 07777);
1584 return 0;
1585 }