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