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