]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/fileio.c
Merge pull request #12628 from keszybz/dbus-execute
[thirdparty/systemd.git] / src / basic / fileio.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
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 <string.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15
16 #include "alloc-util.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 "missing.h"
24 #include "mkdir.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 #include "stdio-util.h"
28 #include "string-util.h"
29 #include "tmpfile-util.h"
30
31 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
32
33 int fopen_unlocked(const char *path, const char *options, FILE **ret) {
34 assert(ret);
35
36 FILE *f = fopen(path, options);
37 if (!f)
38 return -errno;
39
40 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
41
42 *ret = f;
43 return 0;
44 }
45
46 int fdopen_unlocked(int fd, const char *options, FILE **ret) {
47 assert(ret);
48
49 FILE *f = fdopen(fd, options);
50 if (!f)
51 return -errno;
52
53 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
54
55 *ret = f;
56 return 0;
57 }
58
59 FILE* open_memstream_unlocked(char **ptr, size_t *sizeloc) {
60 FILE *f = open_memstream(ptr, sizeloc);
61 if (!f)
62 return NULL;
63
64 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
65
66 return f;
67 }
68
69 FILE* fmemopen_unlocked(void *buf, size_t size, const char *mode) {
70 FILE *f = fmemopen(buf, size, mode);
71 if (!f)
72 return NULL;
73
74 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
75
76 return f;
77 }
78
79 int write_string_stream_ts(
80 FILE *f,
81 const char *line,
82 WriteStringFileFlags flags,
83 struct timespec *ts) {
84
85 bool needs_nl;
86 int r;
87
88 assert(f);
89 assert(line);
90
91 if (ferror(f))
92 return -EIO;
93
94 needs_nl = !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) && !endswith(line, "\n");
95
96 if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) {
97 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
98 * that the write goes out in one go, instead of two */
99
100 line = strjoina(line, "\n");
101 needs_nl = false;
102 }
103
104 if (fputs(line, f) == EOF)
105 return -errno;
106
107 if (needs_nl)
108 if (fputc('\n', f) == EOF)
109 return -errno;
110
111 if (flags & WRITE_STRING_FILE_SYNC)
112 r = fflush_sync_and_check(f);
113 else
114 r = fflush_and_check(f);
115 if (r < 0)
116 return r;
117
118 if (ts) {
119 struct timespec twice[2] = {*ts, *ts};
120
121 if (futimens(fileno(f), twice) < 0)
122 return -errno;
123 }
124
125 return 0;
126 }
127
128 static int write_string_file_atomic(
129 const char *fn,
130 const char *line,
131 WriteStringFileFlags flags,
132 struct timespec *ts) {
133
134 _cleanup_fclose_ FILE *f = NULL;
135 _cleanup_free_ char *p = NULL;
136 int r;
137
138 assert(fn);
139 assert(line);
140
141 r = fopen_temporary(fn, &f, &p);
142 if (r < 0)
143 return r;
144
145 (void) fchmod_umask(fileno(f), 0644);
146
147 r = write_string_stream_ts(f, line, flags, ts);
148 if (r < 0)
149 goto fail;
150
151 if (rename(p, fn) < 0) {
152 r = -errno;
153 goto fail;
154 }
155
156 return 0;
157
158 fail:
159 (void) unlink(p);
160 return r;
161 }
162
163 int write_string_file_ts(
164 const char *fn,
165 const char *line,
166 WriteStringFileFlags flags,
167 struct timespec *ts) {
168
169 _cleanup_fclose_ FILE *f = NULL;
170 int q, r;
171
172 assert(fn);
173 assert(line);
174
175 /* We don't know how to verify whether the file contents was already on-disk. */
176 assert(!((flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE) && (flags & WRITE_STRING_FILE_SYNC)));
177
178 if (flags & WRITE_STRING_FILE_MKDIR_0755) {
179 r = mkdir_parents(fn, 0755);
180 if (r < 0)
181 return r;
182 }
183
184 if (flags & WRITE_STRING_FILE_ATOMIC) {
185 assert(flags & WRITE_STRING_FILE_CREATE);
186
187 r = write_string_file_atomic(fn, line, flags, ts);
188 if (r < 0)
189 goto fail;
190
191 return r;
192 } else
193 assert(!ts);
194
195 if (flags & WRITE_STRING_FILE_CREATE) {
196 r = fopen_unlocked(fn, "we", &f);
197 if (r < 0)
198 goto fail;
199 } else {
200 int fd;
201
202 /* We manually build our own version of fopen(..., "we") that
203 * works without O_CREAT */
204 fd = open(fn, O_WRONLY|O_CLOEXEC|O_NOCTTY | ((flags & WRITE_STRING_FILE_NOFOLLOW) ? O_NOFOLLOW : 0));
205 if (fd < 0) {
206 r = -errno;
207 goto fail;
208 }
209
210 r = fdopen_unlocked(fd, "w", &f);
211 if (r < 0) {
212 safe_close(fd);
213 goto fail;
214 }
215 }
216
217 if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
218 setvbuf(f, NULL, _IONBF, 0);
219
220 r = write_string_stream_ts(f, line, flags, ts);
221 if (r < 0)
222 goto fail;
223
224 return 0;
225
226 fail:
227 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
228 return r;
229
230 f = safe_fclose(f);
231
232 /* OK, the operation failed, but let's see if the right
233 * contents in place already. If so, eat up the error. */
234
235 q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
236 if (q <= 0)
237 return r;
238
239 return 0;
240 }
241
242 int write_string_filef(
243 const char *fn,
244 WriteStringFileFlags flags,
245 const char *format, ...) {
246
247 _cleanup_free_ char *p = NULL;
248 va_list ap;
249 int r;
250
251 va_start(ap, format);
252 r = vasprintf(&p, format, ap);
253 va_end(ap);
254
255 if (r < 0)
256 return -ENOMEM;
257
258 return write_string_file(fn, p, flags);
259 }
260
261 int read_one_line_file(const char *fn, char **line) {
262 _cleanup_fclose_ FILE *f = NULL;
263 int r;
264
265 assert(fn);
266 assert(line);
267
268 r = fopen_unlocked(fn, "re", &f);
269 if (r < 0)
270 return r;
271
272 return read_line(f, LONG_LINE_MAX, line);
273 }
274
275 int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
276 _cleanup_fclose_ FILE *f = NULL;
277 _cleanup_free_ char *buf = NULL;
278 size_t l, k;
279 int r;
280
281 assert(fn);
282 assert(blob);
283
284 l = strlen(blob);
285
286 if (accept_extra_nl && endswith(blob, "\n"))
287 accept_extra_nl = false;
288
289 buf = malloc(l + accept_extra_nl + 1);
290 if (!buf)
291 return -ENOMEM;
292
293 r = fopen_unlocked(fn, "re", &f);
294 if (r < 0)
295 return r;
296
297 /* We try to read one byte more than we need, so that we know whether we hit eof */
298 errno = 0;
299 k = fread(buf, 1, l + accept_extra_nl + 1, f);
300 if (ferror(f))
301 return errno > 0 ? -errno : -EIO;
302
303 if (k != l && k != l + accept_extra_nl)
304 return 0;
305 if (memcmp(buf, blob, l) != 0)
306 return 0;
307 if (k > l && buf[l] != '\n')
308 return 0;
309
310 return 1;
311 }
312
313 int read_full_stream_full(
314 FILE *f,
315 const char *filename,
316 ReadFullFileFlags flags,
317 char **ret_contents,
318 size_t *ret_size) {
319
320 _cleanup_free_ char *buf = NULL;
321 struct stat st;
322 size_t n, n_next, l;
323 int fd, r;
324
325 assert(f);
326 assert(ret_contents);
327 assert(!FLAGS_SET(flags, READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX));
328 assert(!(flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) || ret_size);
329
330 n_next = LINE_MAX; /* Start size */
331
332 fd = fileno(f);
333 if (fd >= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
334 * optimize our buffering) */
335
336 if (fstat(fd, &st) < 0)
337 return -errno;
338
339 if (S_ISREG(st.st_mode)) {
340
341 /* Safety check */
342 if (st.st_size > READ_FULL_BYTES_MAX)
343 return -E2BIG;
344
345 /* Start with the right file size, but be prepared for files from /proc which generally report a file
346 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
347 * already makes us notice the EOF. */
348 if (st.st_size > 0)
349 n_next = st.st_size + 1;
350
351 if (flags & READ_FULL_FILE_SECURE)
352 (void) warn_file_is_world_accessible(filename, &st, NULL, 0);
353 }
354 }
355
356 n = l = 0;
357 for (;;) {
358 char *t;
359 size_t k;
360
361 if (flags & READ_FULL_FILE_SECURE) {
362 t = malloc(n_next + 1);
363 if (!t) {
364 r = -ENOMEM;
365 goto finalize;
366 }
367 memcpy_safe(t, buf, n);
368 explicit_bzero_safe(buf, n);
369 buf = mfree(buf);
370 } else {
371 t = realloc(buf, n_next + 1);
372 if (!t)
373 return -ENOMEM;
374 }
375
376 buf = t;
377 n = n_next;
378
379 errno = 0;
380 k = fread(buf + l, 1, n - l, f);
381 if (k > 0)
382 l += k;
383
384 if (ferror(f)) {
385 r = errno > 0 ? -errno : -EIO;
386 goto finalize;
387 }
388
389 if (feof(f))
390 break;
391
392 /* We aren't expecting fread() to return a short read outside
393 * of (error && eof), assert buffer is full and enlarge buffer.
394 */
395 assert(l == n);
396
397 /* Safety check */
398 if (n >= READ_FULL_BYTES_MAX) {
399 r = -E2BIG;
400 goto finalize;
401 }
402
403 n_next = MIN(n * 2, READ_FULL_BYTES_MAX);
404 }
405
406 if (flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) {
407 buf[l++] = 0;
408 if (flags & READ_FULL_FILE_UNBASE64)
409 r = unbase64mem_full(buf, l, flags & READ_FULL_FILE_SECURE, (void **) ret_contents, ret_size);
410 else
411 r = unhexmem_full(buf, l, flags & READ_FULL_FILE_SECURE, (void **) ret_contents, ret_size);
412 goto finalize;
413 }
414
415 if (!ret_size) {
416 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
417 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
418 * there'd be ambiguity about what we just read. */
419
420 if (memchr(buf, 0, l)) {
421 r = -EBADMSG;
422 goto finalize;
423 }
424 }
425
426 buf[l] = 0;
427 *ret_contents = TAKE_PTR(buf);
428
429 if (ret_size)
430 *ret_size = l;
431
432 return 0;
433
434 finalize:
435 if (flags & READ_FULL_FILE_SECURE)
436 explicit_bzero_safe(buf, n);
437
438 return r;
439 }
440
441 int read_full_file_full(const char *filename, ReadFullFileFlags flags, char **contents, size_t *size) {
442 _cleanup_fclose_ FILE *f = NULL;
443 int r;
444
445 assert(filename);
446 assert(contents);
447
448 r = fopen_unlocked(filename, "re", &f);
449 if (r < 0)
450 return r;
451
452 return read_full_stream_full(f, filename, flags, contents, size);
453 }
454
455 int executable_is_script(const char *path, char **interpreter) {
456 _cleanup_free_ char *line = NULL;
457 size_t len;
458 char *ans;
459 int r;
460
461 assert(path);
462
463 r = read_one_line_file(path, &line);
464 if (r == -ENOBUFS) /* First line overly long? if so, then it's not a script */
465 return 0;
466 if (r < 0)
467 return r;
468
469 if (!startswith(line, "#!"))
470 return 0;
471
472 ans = strstrip(line + 2);
473 len = strcspn(ans, " \t");
474
475 if (len == 0)
476 return 0;
477
478 ans = strndup(ans, len);
479 if (!ans)
480 return -ENOMEM;
481
482 *interpreter = ans;
483 return 1;
484 }
485
486 /**
487 * Retrieve one field from a file like /proc/self/status. pattern
488 * should not include whitespace or the delimiter (':'). pattern matches only
489 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
490 * zeros after the ':' will be skipped. field must be freed afterwards.
491 * terminator specifies the terminating characters of the field value (not
492 * included in the value).
493 */
494 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
495 _cleanup_free_ char *status = NULL;
496 char *t, *f;
497 size_t len;
498 int r;
499
500 assert(terminator);
501 assert(filename);
502 assert(pattern);
503 assert(field);
504
505 r = read_full_file(filename, &status, NULL);
506 if (r < 0)
507 return r;
508
509 t = status;
510
511 do {
512 bool pattern_ok;
513
514 do {
515 t = strstr(t, pattern);
516 if (!t)
517 return -ENOENT;
518
519 /* Check that pattern occurs in beginning of line. */
520 pattern_ok = (t == status || t[-1] == '\n');
521
522 t += strlen(pattern);
523
524 } while (!pattern_ok);
525
526 t += strspn(t, " \t");
527 if (!*t)
528 return -ENOENT;
529
530 } while (*t != ':');
531
532 t++;
533
534 if (*t) {
535 t += strspn(t, " \t");
536
537 /* Also skip zeros, because when this is used for
538 * capabilities, we don't want the zeros. This way the
539 * same capability set always maps to the same string,
540 * irrespective of the total capability set size. For
541 * other numbers it shouldn't matter. */
542 t += strspn(t, "0");
543 /* Back off one char if there's nothing but whitespace
544 and zeros */
545 if (!*t || isspace(*t))
546 t--;
547 }
548
549 len = strcspn(t, terminator);
550
551 f = strndup(t, len);
552 if (!f)
553 return -ENOMEM;
554
555 *field = f;
556 return 0;
557 }
558
559 DIR *xopendirat(int fd, const char *name, int flags) {
560 int nfd;
561 DIR *d;
562
563 assert(!(flags & O_CREAT));
564
565 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
566 if (nfd < 0)
567 return NULL;
568
569 d = fdopendir(nfd);
570 if (!d) {
571 safe_close(nfd);
572 return NULL;
573 }
574
575 return d;
576 }
577
578 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
579 char **i;
580
581 assert(path);
582 assert(mode);
583 assert(_f);
584
585 if (!path_strv_resolve_uniq(search, root))
586 return -ENOMEM;
587
588 STRV_FOREACH(i, search) {
589 _cleanup_free_ char *p = NULL;
590 FILE *f;
591
592 if (root)
593 p = strjoin(root, *i, "/", path);
594 else
595 p = strjoin(*i, "/", path);
596 if (!p)
597 return -ENOMEM;
598
599 f = fopen(p, mode);
600 if (f) {
601 *_f = f;
602 return 0;
603 }
604
605 if (errno != ENOENT)
606 return -errno;
607 }
608
609 return -ENOENT;
610 }
611
612 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
613 _cleanup_strv_free_ char **copy = NULL;
614
615 assert(path);
616 assert(mode);
617 assert(_f);
618
619 if (path_is_absolute(path)) {
620 FILE *f;
621
622 f = fopen(path, mode);
623 if (f) {
624 *_f = f;
625 return 0;
626 }
627
628 return -errno;
629 }
630
631 copy = strv_copy((char**) search);
632 if (!copy)
633 return -ENOMEM;
634
635 return search_and_fopen_internal(path, mode, root, copy, _f);
636 }
637
638 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
639 _cleanup_strv_free_ char **s = NULL;
640
641 if (path_is_absolute(path)) {
642 FILE *f;
643
644 f = fopen(path, mode);
645 if (f) {
646 *_f = f;
647 return 0;
648 }
649
650 return -errno;
651 }
652
653 s = strv_split_nulstr(search);
654 if (!s)
655 return -ENOMEM;
656
657 return search_and_fopen_internal(path, mode, root, s, _f);
658 }
659
660 int fflush_and_check(FILE *f) {
661 assert(f);
662
663 errno = 0;
664 fflush(f);
665
666 if (ferror(f))
667 return errno > 0 ? -errno : -EIO;
668
669 return 0;
670 }
671
672 int fflush_sync_and_check(FILE *f) {
673 int r;
674
675 assert(f);
676
677 r = fflush_and_check(f);
678 if (r < 0)
679 return r;
680
681 if (fsync(fileno(f)) < 0)
682 return -errno;
683
684 r = fsync_directory_of_file(fileno(f));
685 if (r < 0)
686 return r;
687
688 return 0;
689 }
690
691 int write_timestamp_file_atomic(const char *fn, usec_t n) {
692 char ln[DECIMAL_STR_MAX(n)+2];
693
694 /* Creates a "timestamp" file, that contains nothing but a
695 * usec_t timestamp, formatted in ASCII. */
696
697 if (n <= 0 || n >= USEC_INFINITY)
698 return -ERANGE;
699
700 xsprintf(ln, USEC_FMT "\n", n);
701
702 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
703 }
704
705 int read_timestamp_file(const char *fn, usec_t *ret) {
706 _cleanup_free_ char *ln = NULL;
707 uint64_t t;
708 int r;
709
710 r = read_one_line_file(fn, &ln);
711 if (r < 0)
712 return r;
713
714 r = safe_atou64(ln, &t);
715 if (r < 0)
716 return r;
717
718 if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
719 return -ERANGE;
720
721 *ret = (usec_t) t;
722 return 0;
723 }
724
725 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
726 int r;
727
728 assert(s);
729
730 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
731 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
732 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
733 * element, but not before the first one. */
734
735 if (!f)
736 f = stdout;
737
738 if (space) {
739 if (!separator)
740 separator = " ";
741
742 if (*space) {
743 r = fputs(separator, f);
744 if (r < 0)
745 return r;
746 }
747
748 *space = true;
749 }
750
751 return fputs(s, f);
752 }
753
754 /* A bitmask of the EOL markers we know */
755 typedef enum EndOfLineMarker {
756 EOL_NONE = 0,
757 EOL_ZERO = 1 << 0, /* \0 (aka NUL) */
758 EOL_TEN = 1 << 1, /* \n (aka NL, aka LF) */
759 EOL_THIRTEEN = 1 << 2, /* \r (aka CR) */
760 } EndOfLineMarker;
761
762 static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) {
763
764 if (!IN_SET(flags, READ_LINE_ONLY_NUL)) {
765 if (c == '\n')
766 return EOL_TEN;
767 if (c == '\r')
768 return EOL_THIRTEEN;
769 }
770
771 if (c == '\0')
772 return EOL_ZERO;
773
774 return EOL_NONE;
775 }
776
777 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile);
778
779 int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) {
780 size_t n = 0, allocated = 0, count = 0;
781 _cleanup_free_ char *buffer = NULL;
782 int r;
783
784 assert(f);
785
786 /* Something like a bounded version of getline().
787 *
788 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
789 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
790 * endings:
791 *
792 * • \n (UNIX)
793 * • \r (old MacOS)
794 * • \0 (C strings)
795 * • \n\0
796 * • \r\0
797 * • \r\n (Windows)
798 * • \n\r
799 * • \r\n\0
800 * • \n\r\0
801 *
802 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
803 * the number of characters in the returned string). When EOF is hit, 0 is returned.
804 *
805 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
806 * delimiters. If the limit is hit we fail and return -ENOBUFS.
807 *
808 * If a line shall be skipped ret may be initialized as NULL. */
809
810 if (ret) {
811 if (!GREEDY_REALLOC(buffer, allocated, 1))
812 return -ENOMEM;
813 }
814
815 {
816 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
817 EndOfLineMarker previous_eol = EOL_NONE;
818 flockfile(f);
819
820 for (;;) {
821 EndOfLineMarker eol;
822 char c;
823
824 if (n >= limit)
825 return -ENOBUFS;
826
827 if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */
828 return -ENOBUFS;
829
830 r = safe_fgetc(f, &c);
831 if (r < 0)
832 return r;
833 if (r == 0) /* EOF is definitely EOL */
834 break;
835
836 eol = categorize_eol(c, flags);
837
838 if (FLAGS_SET(previous_eol, EOL_ZERO) ||
839 (eol == EOL_NONE && previous_eol != EOL_NONE) ||
840 (eol != EOL_NONE && (previous_eol & eol) != 0)) {
841 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
842 * EOL marker has been seen right before? In either of these three cases we are
843 * done. But first, let's put this character back in the queue. (Note that we have to
844 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
845 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
846 * pass a negative value here. That said, to complicate things further ungetc() is
847 * actually happy with most negative characters and implicitly casts them back to
848 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
849 * godawful API!) */
850 assert_se(ungetc((unsigned char) c, f) != EOF);
851 break;
852 }
853
854 count++;
855
856 if (eol != EOL_NONE) {
857 previous_eol |= eol;
858 continue;
859 }
860
861 if (ret) {
862 if (!GREEDY_REALLOC(buffer, allocated, n + 2))
863 return -ENOMEM;
864
865 buffer[n] = c;
866 }
867
868 n++;
869 }
870 }
871
872 if (ret) {
873 buffer[n] = 0;
874
875 *ret = TAKE_PTR(buffer);
876 }
877
878 return (int) count;
879 }
880
881 int safe_fgetc(FILE *f, char *ret) {
882 int k;
883
884 assert(f);
885
886 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
887 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
888 * has. */
889
890 errno = 0;
891 k = fgetc(f);
892 if (k == EOF) {
893 if (ferror(f))
894 return errno > 0 ? -errno : -EIO;
895
896 if (ret)
897 *ret = 0;
898
899 return 0;
900 }
901
902 if (ret)
903 *ret = k;
904
905 return 1;
906 }
907
908 int warn_file_is_world_accessible(const char *filename, struct stat *st, const char *unit, unsigned line) {
909 struct stat _st;
910
911 if (!filename)
912 return 0;
913
914 if (!st) {
915 if (stat(filename, &_st) < 0)
916 return -errno;
917 st = &_st;
918 }
919
920 if ((st->st_mode & S_IRWXO) == 0)
921 return 0;
922
923 if (unit)
924 log_syntax(unit, LOG_WARNING, filename, line, 0,
925 "%s has %04o mode that is too permissive, please adjust the access mode.",
926 filename, st->st_mode & 07777);
927 else
928 log_warning("%s has %04o mode that is too permissive, please adjust the access mode.",
929 filename, st->st_mode & 07777);
930 return 0;
931 }