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