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