]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/fileio.c
alloc-util: simplify GREEDY_REALLOC() logic by relying on malloc_usable_size()
[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_virtual_file(const char *filename, size_t max_size, char **ret_contents, size_t *ret_size) {
368 _cleanup_free_ char *buf = NULL;
369 _cleanup_close_ int fd = -1;
370 size_t n, size;
371 int n_retries;
372 bool truncated = false;
373
374 assert(ret_contents);
375
376 /* Virtual filesystems such as sysfs or procfs use kernfs, and kernfs can work with two sorts of
377 * virtual files. One sort uses "seq_file", and the results of the first read are buffered for the
378 * second read. The other sort uses "raw" reads which always go direct to the device. In the latter
379 * case, the content of 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 why the usage of
381 * fread(3) is prohibited in this case as it always performs a second call to read(2) looking for
382 * EOF. See issue #13585.
383 *
384 * max_size specifies a limit on the bytes read. If max_size is SIZE_MAX, the full file is read. If
385 * the the full file is too large to read, an error is returned. For other values of max_size,
386 * *partial contents* may be returned. (Though the read is still done using one syscall.)
387 * Returns 0 on partial success, 1 if untruncated contents were read. */
388
389 fd = open(filename, O_RDONLY|O_CLOEXEC);
390 if (fd < 0)
391 return -errno;
392
393 assert(max_size <= READ_FULL_BYTES_MAX || max_size == SIZE_MAX);
394
395 /* Limit the number of attempts to read the number of bytes returned by fstat(). */
396 n_retries = 3;
397
398 for (;;) {
399 struct stat st;
400
401 if (fstat(fd, &st) < 0)
402 return -errno;
403
404 if (!S_ISREG(st.st_mode))
405 return -EBADF;
406
407 /* Be prepared for files from /proc which generally report a file size of 0. */
408 assert_cc(READ_FULL_BYTES_MAX < SSIZE_MAX);
409 if (st.st_size > 0) {
410 if (st.st_size > SSIZE_MAX) /* Avoid overflow with 32-bit size_t and 64-bit off_t. */
411 return -EFBIG;
412
413 size = MIN((size_t) st.st_size, max_size);
414 if (size > READ_FULL_BYTES_MAX)
415 return -EFBIG;
416
417 n_retries--;
418 } else {
419 size = MIN(READ_FULL_BYTES_MAX, max_size);
420 n_retries = 0;
421 }
422
423 buf = malloc(size + 1);
424 if (!buf)
425 return -ENOMEM;
426 /* Use a bigger allocation if we got it anyway, but not more than the limit. */
427 size = MIN3(MALLOC_SIZEOF_SAFE(buf) - 1, max_size, READ_FULL_BYTES_MAX);
428
429 for (;;) {
430 ssize_t k;
431
432 /* Read one more byte so we can detect whether the content of the
433 * file has already changed or the guessed size for files from /proc
434 * wasn't large enough . */
435 k = read(fd, buf, size + 1);
436 if (k >= 0) {
437 n = k;
438 break;
439 }
440
441 if (errno != EINTR)
442 return -errno;
443 }
444
445 /* Consider a short read as EOF */
446 if (n <= size)
447 break;
448
449 /* Hmm... either we read too few bytes from /proc or less likely the content
450 * of the file might have been changed (and is now bigger) while we were
451 * processing, let's try again either with a bigger guessed size or the new
452 * file size. */
453
454 if (n_retries <= 0) {
455 if (max_size == SIZE_MAX)
456 return st.st_size > 0 ? -EIO : -EFBIG;
457
458 /* Accept a short read, but truncate it appropropriately. */
459 n = MIN(n, max_size);
460 truncated = true;
461 break;
462 }
463
464 if (lseek(fd, 0, SEEK_SET) < 0)
465 return -errno;
466
467 buf = mfree(buf);
468 }
469
470 if (n < size) {
471 char *p;
472
473 /* Return rest of the buffer to libc */
474 p = realloc(buf, n + 1);
475 if (!p)
476 return -ENOMEM;
477 buf = p;
478 }
479
480 if (ret_size)
481 *ret_size = n;
482 else if (memchr(buf, 0, n))
483 /* Safety check: if the caller doesn't want to know the size of what we just read it will
484 * rely on the trailing NUL byte. But if there's an embedded NUL byte, then we should refuse
485 * operation as otherwise there'd be ambiguity about what we just read. */
486 return -EBADMSG;
487
488 buf[n] = 0;
489 *ret_contents = TAKE_PTR(buf);
490
491 return !truncated;
492 }
493
494 int read_full_stream_full(
495 FILE *f,
496 const char *filename,
497 uint64_t offset,
498 size_t size,
499 ReadFullFileFlags flags,
500 char **ret_contents,
501 size_t *ret_size) {
502
503 _cleanup_free_ char *buf = NULL;
504 size_t n, n_next, l;
505 int fd, r;
506
507 assert(f);
508 assert(ret_contents);
509 assert(!FLAGS_SET(flags, READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX));
510
511 if (offset != UINT64_MAX && offset > LONG_MAX)
512 return -ERANGE;
513
514 n_next = size != SIZE_MAX ? size : LINE_MAX; /* Start size */
515
516 fd = fileno(f);
517 if (fd >= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see
518 * fmemopen()), let's optimize our buffering */
519 struct stat st;
520
521 if (fstat(fd, &st) < 0)
522 return -errno;
523
524 if (S_ISREG(st.st_mode)) {
525 if (size == SIZE_MAX) {
526 uint64_t rsize =
527 LESS_BY((uint64_t) st.st_size, offset == UINT64_MAX ? 0 : offset);
528
529 /* Safety check */
530 if (rsize > READ_FULL_BYTES_MAX)
531 return -E2BIG;
532
533 /* Start with the right file size. Note that we increase the size to read
534 * here by one, so that the first read attempt already makes us notice the
535 * EOF. If the reported size of the file is zero, we avoid this logic
536 * however, since quite likely it might be a virtual file in procfs that all
537 * report a zero file size. */
538 if (st.st_size > 0)
539 n_next = rsize + 1;
540 }
541
542 if (flags & READ_FULL_FILE_WARN_WORLD_READABLE)
543 (void) warn_file_is_world_accessible(filename, &st, NULL, 0);
544 }
545 }
546
547 if (offset != UINT64_MAX && fseek(f, offset, SEEK_SET) < 0)
548 return -errno;
549
550 n = l = 0;
551 for (;;) {
552 char *t;
553 size_t k;
554
555 if (flags & READ_FULL_FILE_SECURE) {
556 t = malloc(n_next + 1);
557 if (!t) {
558 r = -ENOMEM;
559 goto finalize;
560 }
561 memcpy_safe(t, buf, n);
562 explicit_bzero_safe(buf, n);
563 buf = mfree(buf);
564 } else {
565 t = realloc(buf, n_next + 1);
566 if (!t)
567 return -ENOMEM;
568 }
569
570 buf = t;
571 /* Unless a size has been explicitly specified, try to read as much as fits into the memory
572 * we allocated (minus 1, to leave one byte for the safety NUL byte) */
573 n = size == SIZE_MAX ? MALLOC_SIZEOF_SAFE(buf) - 1 : n_next;
574
575 errno = 0;
576 k = fread(buf + l, 1, n - l, f);
577
578 assert(k <= n - l);
579 l += k;
580
581 if (ferror(f)) {
582 r = errno_or_else(EIO);
583 goto finalize;
584 }
585 if (feof(f))
586 break;
587
588 if (size != SIZE_MAX) { /* If we got asked to read some specific size, we already sized the buffer right, hence leave */
589 assert(l == size);
590 break;
591 }
592
593 assert(k > 0); /* we can't have read zero bytes because that would have been EOF */
594
595 /* Safety check */
596 if (n >= READ_FULL_BYTES_MAX) {
597 r = -E2BIG;
598 goto finalize;
599 }
600
601 n_next = MIN(n * 2, READ_FULL_BYTES_MAX);
602 }
603
604 if (flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) {
605 _cleanup_free_ void *decoded = NULL;
606 size_t decoded_size;
607
608 buf[l++] = 0;
609 if (flags & READ_FULL_FILE_UNBASE64)
610 r = unbase64mem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size);
611 else
612 r = unhexmem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size);
613 if (r < 0)
614 goto finalize;
615
616 if (flags & READ_FULL_FILE_SECURE)
617 explicit_bzero_safe(buf, n);
618 free_and_replace(buf, decoded);
619 n = l = decoded_size;
620 }
621
622 if (!ret_size) {
623 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
624 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
625 * there'd be ambiguity about what we just read. */
626
627 if (memchr(buf, 0, l)) {
628 r = -EBADMSG;
629 goto finalize;
630 }
631 }
632
633 buf[l] = 0;
634 *ret_contents = TAKE_PTR(buf);
635
636 if (ret_size)
637 *ret_size = l;
638
639 return 0;
640
641 finalize:
642 if (flags & READ_FULL_FILE_SECURE)
643 explicit_bzero_safe(buf, n);
644
645 return r;
646 }
647
648 int read_full_file_full(
649 int dir_fd,
650 const char *filename,
651 uint64_t offset,
652 size_t size,
653 ReadFullFileFlags flags,
654 const char *bind_name,
655 char **ret_contents,
656 size_t *ret_size) {
657
658 _cleanup_fclose_ FILE *f = NULL;
659 int r;
660
661 assert(filename);
662 assert(ret_contents);
663
664 r = xfopenat(dir_fd, filename, "re", 0, &f);
665 if (r < 0) {
666 _cleanup_close_ int dfd = -1, sk = -1;
667 union sockaddr_union sa;
668
669 /* ENXIO is what Linux returns if we open a node that is an AF_UNIX socket */
670 if (r != -ENXIO)
671 return r;
672
673 /* If this is enabled, let's try to connect to it */
674 if (!FLAGS_SET(flags, READ_FULL_FILE_CONNECT_SOCKET))
675 return -ENXIO;
676
677 /* Seeking is not supported on AF_UNIX sockets */
678 if (offset != UINT64_MAX)
679 return -ESPIPE;
680
681 if (dir_fd == AT_FDCWD)
682 r = sockaddr_un_set_path(&sa.un, filename);
683 else {
684 char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
685
686 /* If we shall operate relative to some directory, then let's use O_PATH first to
687 * open the socket inode, and then connect to it via /proc/self/fd/. We have to do
688 * this since there's not connectat() that takes a directory fd as first arg. */
689
690 dfd = openat(dir_fd, filename, O_PATH|O_CLOEXEC);
691 if (dfd < 0)
692 return -errno;
693
694 xsprintf(procfs_path, "/proc/self/fd/%i", dfd);
695 r = sockaddr_un_set_path(&sa.un, procfs_path);
696 }
697 if (r < 0)
698 return r;
699
700 sk = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
701 if (sk < 0)
702 return -errno;
703
704 if (bind_name) {
705 /* If the caller specified a socket name to bind to, do so before connecting. This is
706 * useful to communicate some minor, short meta-information token from the client to
707 * the server. */
708 union sockaddr_union bsa;
709
710 r = sockaddr_un_set_path(&bsa.un, bind_name);
711 if (r < 0)
712 return r;
713
714 if (bind(sk, &bsa.sa, r) < 0)
715 return r;
716 }
717
718 if (connect(sk, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0)
719 return errno == ENOTSOCK ? -ENXIO : -errno; /* propagate original error if this is
720 * not a socket after all */
721
722 if (shutdown(sk, SHUT_WR) < 0)
723 return -errno;
724
725 f = fdopen(sk, "r");
726 if (!f)
727 return -errno;
728
729 TAKE_FD(sk);
730 }
731
732 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
733
734 return read_full_stream_full(f, filename, offset, size, flags, ret_contents, ret_size);
735 }
736
737 int executable_is_script(const char *path, char **interpreter) {
738 _cleanup_free_ char *line = NULL;
739 size_t len;
740 char *ans;
741 int r;
742
743 assert(path);
744
745 r = read_one_line_file(path, &line);
746 if (r == -ENOBUFS) /* First line overly long? if so, then it's not a script */
747 return 0;
748 if (r < 0)
749 return r;
750
751 if (!startswith(line, "#!"))
752 return 0;
753
754 ans = strstrip(line + 2);
755 len = strcspn(ans, " \t");
756
757 if (len == 0)
758 return 0;
759
760 ans = strndup(ans, len);
761 if (!ans)
762 return -ENOMEM;
763
764 *interpreter = ans;
765 return 1;
766 }
767
768 /**
769 * Retrieve one field from a file like /proc/self/status. pattern
770 * should not include whitespace or the delimiter (':'). pattern matches only
771 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
772 * zeros after the ':' will be skipped. field must be freed afterwards.
773 * terminator specifies the terminating characters of the field value (not
774 * included in the value).
775 */
776 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
777 _cleanup_free_ char *status = NULL;
778 char *t, *f;
779 size_t len;
780 int r;
781
782 assert(terminator);
783 assert(filename);
784 assert(pattern);
785 assert(field);
786
787 r = read_full_virtual_file(filename, &status, NULL);
788 if (r < 0)
789 return r;
790
791 t = status;
792
793 do {
794 bool pattern_ok;
795
796 do {
797 t = strstr(t, pattern);
798 if (!t)
799 return -ENOENT;
800
801 /* Check that pattern occurs in beginning of line. */
802 pattern_ok = (t == status || t[-1] == '\n');
803
804 t += strlen(pattern);
805
806 } while (!pattern_ok);
807
808 t += strspn(t, " \t");
809 if (!*t)
810 return -ENOENT;
811
812 } while (*t != ':');
813
814 t++;
815
816 if (*t) {
817 t += strspn(t, " \t");
818
819 /* Also skip zeros, because when this is used for
820 * capabilities, we don't want the zeros. This way the
821 * same capability set always maps to the same string,
822 * irrespective of the total capability set size. For
823 * other numbers it shouldn't matter. */
824 t += strspn(t, "0");
825 /* Back off one char if there's nothing but whitespace
826 and zeros */
827 if (!*t || isspace(*t))
828 t--;
829 }
830
831 len = strcspn(t, terminator);
832
833 f = strndup(t, len);
834 if (!f)
835 return -ENOMEM;
836
837 *field = f;
838 return 0;
839 }
840
841 DIR *xopendirat(int fd, const char *name, int flags) {
842 int nfd;
843 DIR *d;
844
845 assert(!(flags & O_CREAT));
846
847 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
848 if (nfd < 0)
849 return NULL;
850
851 d = fdopendir(nfd);
852 if (!d) {
853 safe_close(nfd);
854 return NULL;
855 }
856
857 return d;
858 }
859
860 static int mode_to_flags(const char *mode) {
861 const char *p;
862 int flags;
863
864 if ((p = startswith(mode, "r+")))
865 flags = O_RDWR;
866 else if ((p = startswith(mode, "r")))
867 flags = O_RDONLY;
868 else if ((p = startswith(mode, "w+")))
869 flags = O_RDWR|O_CREAT|O_TRUNC;
870 else if ((p = startswith(mode, "w")))
871 flags = O_WRONLY|O_CREAT|O_TRUNC;
872 else if ((p = startswith(mode, "a+")))
873 flags = O_RDWR|O_CREAT|O_APPEND;
874 else if ((p = startswith(mode, "a")))
875 flags = O_WRONLY|O_CREAT|O_APPEND;
876 else
877 return -EINVAL;
878
879 for (; *p != 0; p++) {
880
881 switch (*p) {
882
883 case 'e':
884 flags |= O_CLOEXEC;
885 break;
886
887 case 'x':
888 flags |= O_EXCL;
889 break;
890
891 case 'm':
892 /* ignore this here, fdopen() might care later though */
893 break;
894
895 case 'c': /* not sure what to do about this one */
896 default:
897 return -EINVAL;
898 }
899 }
900
901 return flags;
902 }
903
904 int xfopenat(int dir_fd, const char *path, const char *mode, int flags, FILE **ret) {
905 FILE *f;
906
907 /* A combination of fopen() with openat() */
908
909 if (dir_fd == AT_FDCWD && flags == 0) {
910 f = fopen(path, mode);
911 if (!f)
912 return -errno;
913 } else {
914 int fd, mode_flags;
915
916 mode_flags = mode_to_flags(mode);
917 if (mode_flags < 0)
918 return mode_flags;
919
920 fd = openat(dir_fd, path, mode_flags | flags);
921 if (fd < 0)
922 return -errno;
923
924 f = fdopen(fd, mode);
925 if (!f) {
926 safe_close(fd);
927 return -errno;
928 }
929 }
930
931 *ret = f;
932 return 0;
933 }
934
935 static int search_and_fopen_internal(
936 const char *path,
937 const char *mode,
938 const char *root,
939 char **search,
940 FILE **ret,
941 char **ret_path) {
942
943 char **i;
944
945 assert(path);
946 assert(mode);
947 assert(ret);
948
949 if (!path_strv_resolve_uniq(search, root))
950 return -ENOMEM;
951
952 STRV_FOREACH(i, search) {
953 _cleanup_free_ char *p = NULL;
954 FILE *f;
955
956 p = path_join(root, *i, path);
957 if (!p)
958 return -ENOMEM;
959
960 f = fopen(p, mode);
961 if (f) {
962 if (ret_path)
963 *ret_path = path_simplify(TAKE_PTR(p), true);
964
965 *ret = f;
966 return 0;
967 }
968
969 if (errno != ENOENT)
970 return -errno;
971 }
972
973 return -ENOENT;
974 }
975
976 int search_and_fopen(
977 const char *filename,
978 const char *mode,
979 const char *root,
980 const char **search,
981 FILE **ret,
982 char **ret_path) {
983
984 _cleanup_strv_free_ char **copy = NULL;
985
986 assert(filename);
987 assert(mode);
988 assert(ret);
989
990 if (path_is_absolute(filename)) {
991 _cleanup_fclose_ FILE *f = NULL;
992
993 f = fopen(filename, mode);
994 if (!f)
995 return -errno;
996
997 if (ret_path) {
998 char *p;
999
1000 p = strdup(filename);
1001 if (!p)
1002 return -ENOMEM;
1003
1004 *ret_path = path_simplify(p, true);
1005 }
1006
1007 *ret = TAKE_PTR(f);
1008 return 0;
1009 }
1010
1011 copy = strv_copy((char**) search);
1012 if (!copy)
1013 return -ENOMEM;
1014
1015 return search_and_fopen_internal(filename, mode, root, copy, ret, ret_path);
1016 }
1017
1018 int search_and_fopen_nulstr(
1019 const char *filename,
1020 const char *mode,
1021 const char *root,
1022 const char *search,
1023 FILE **ret,
1024 char **ret_path) {
1025
1026 _cleanup_strv_free_ char **s = NULL;
1027
1028 if (path_is_absolute(filename)) {
1029 _cleanup_fclose_ FILE *f = NULL;
1030
1031 f = fopen(filename, mode);
1032 if (!f)
1033 return -errno;
1034
1035 if (ret_path) {
1036 char *p;
1037
1038 p = strdup(filename);
1039 if (!p)
1040 return -ENOMEM;
1041
1042 *ret_path = path_simplify(p, true);
1043 }
1044
1045 *ret = TAKE_PTR(f);
1046 return 0;
1047 }
1048
1049 s = strv_split_nulstr(search);
1050 if (!s)
1051 return -ENOMEM;
1052
1053 return search_and_fopen_internal(filename, mode, root, s, ret, ret_path);
1054 }
1055
1056 int chase_symlinks_and_fopen_unlocked(
1057 const char *path,
1058 const char *root,
1059 unsigned chase_flags,
1060 const char *open_flags,
1061 FILE **ret_file,
1062 char **ret_path) {
1063
1064 _cleanup_close_ int fd = -1;
1065 _cleanup_free_ char *final_path = NULL;
1066 int mode_flags, r;
1067
1068 assert(path);
1069 assert(open_flags);
1070 assert(ret_file);
1071
1072 mode_flags = mode_to_flags(open_flags);
1073 if (mode_flags < 0)
1074 return mode_flags;
1075
1076 fd = chase_symlinks_and_open(path, root, chase_flags, mode_flags, ret_path ? &final_path : NULL);
1077 if (fd < 0)
1078 return fd;
1079
1080 r = take_fdopen_unlocked(&fd, open_flags, ret_file);
1081 if (r < 0)
1082 return r;
1083
1084 if (ret_path)
1085 *ret_path = TAKE_PTR(final_path);
1086 return 0;
1087 }
1088
1089 int fflush_and_check(FILE *f) {
1090 assert(f);
1091
1092 errno = 0;
1093 fflush(f);
1094
1095 if (ferror(f))
1096 return errno_or_else(EIO);
1097
1098 return 0;
1099 }
1100
1101 int fflush_sync_and_check(FILE *f) {
1102 int r, fd;
1103
1104 assert(f);
1105
1106 r = fflush_and_check(f);
1107 if (r < 0)
1108 return r;
1109
1110 /* Not all file streams have an fd associated (think: fmemopen()), let's handle this gracefully and
1111 * assume that in that case we need no explicit syncing */
1112 fd = fileno(f);
1113 if (fd < 0)
1114 return 0;
1115
1116 if (fsync(fd) < 0)
1117 return -errno;
1118
1119 r = fsync_directory_of_file(fd);
1120 if (r < 0)
1121 return r;
1122
1123 return 0;
1124 }
1125
1126 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1127 char ln[DECIMAL_STR_MAX(n)+2];
1128
1129 /* Creates a "timestamp" file, that contains nothing but a
1130 * usec_t timestamp, formatted in ASCII. */
1131
1132 if (n <= 0 || n >= USEC_INFINITY)
1133 return -ERANGE;
1134
1135 xsprintf(ln, USEC_FMT "\n", n);
1136
1137 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1138 }
1139
1140 int read_timestamp_file(const char *fn, usec_t *ret) {
1141 _cleanup_free_ char *ln = NULL;
1142 uint64_t t;
1143 int r;
1144
1145 r = read_one_line_file(fn, &ln);
1146 if (r < 0)
1147 return r;
1148
1149 r = safe_atou64(ln, &t);
1150 if (r < 0)
1151 return r;
1152
1153 if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1154 return -ERANGE;
1155
1156 *ret = (usec_t) t;
1157 return 0;
1158 }
1159
1160 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1161 int r;
1162
1163 assert(s);
1164
1165 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1166 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1167 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1168 * element, but not before the first one. */
1169
1170 if (!f)
1171 f = stdout;
1172
1173 if (space) {
1174 if (!separator)
1175 separator = " ";
1176
1177 if (*space) {
1178 r = fputs(separator, f);
1179 if (r < 0)
1180 return r;
1181 }
1182
1183 *space = true;
1184 }
1185
1186 return fputs(s, f);
1187 }
1188
1189 /* A bitmask of the EOL markers we know */
1190 typedef enum EndOfLineMarker {
1191 EOL_NONE = 0,
1192 EOL_ZERO = 1 << 0, /* \0 (aka NUL) */
1193 EOL_TEN = 1 << 1, /* \n (aka NL, aka LF) */
1194 EOL_THIRTEEN = 1 << 2, /* \r (aka CR) */
1195 } EndOfLineMarker;
1196
1197 static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) {
1198
1199 if (!IN_SET(flags, READ_LINE_ONLY_NUL)) {
1200 if (c == '\n')
1201 return EOL_TEN;
1202 if (c == '\r')
1203 return EOL_THIRTEEN;
1204 }
1205
1206 if (c == '\0')
1207 return EOL_ZERO;
1208
1209 return EOL_NONE;
1210 }
1211
1212 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile, NULL);
1213
1214 int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) {
1215 _cleanup_free_ char *buffer = NULL;
1216 size_t n = 0, count = 0;
1217 int r;
1218
1219 assert(f);
1220
1221 /* Something like a bounded version of getline().
1222 *
1223 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
1224 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
1225 * endings:
1226 *
1227 * • \n (UNIX)
1228 * • \r (old MacOS)
1229 * • \0 (C strings)
1230 * • \n\0
1231 * • \r\0
1232 * • \r\n (Windows)
1233 * • \n\r
1234 * • \r\n\0
1235 * • \n\r\0
1236 *
1237 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1238 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1239 *
1240 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1241 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1242 *
1243 * If a line shall be skipped ret may be initialized as NULL. */
1244
1245 if (ret) {
1246 if (!GREEDY_REALLOC(buffer, 1))
1247 return -ENOMEM;
1248 }
1249
1250 {
1251 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
1252 EndOfLineMarker previous_eol = EOL_NONE;
1253 flockfile(f);
1254
1255 for (;;) {
1256 EndOfLineMarker eol;
1257 char c;
1258
1259 if (n >= limit)
1260 return -ENOBUFS;
1261
1262 if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */
1263 return -ENOBUFS;
1264
1265 r = safe_fgetc(f, &c);
1266 if (r < 0)
1267 return r;
1268 if (r == 0) /* EOF is definitely EOL */
1269 break;
1270
1271 eol = categorize_eol(c, flags);
1272
1273 if (FLAGS_SET(previous_eol, EOL_ZERO) ||
1274 (eol == EOL_NONE && previous_eol != EOL_NONE) ||
1275 (eol != EOL_NONE && (previous_eol & eol) != 0)) {
1276 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
1277 * EOL marker has been seen right before? In either of these three cases we are
1278 * done. But first, let's put this character back in the queue. (Note that we have to
1279 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
1280 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
1281 * pass a negative value here. That said, to complicate things further ungetc() is
1282 * actually happy with most negative characters and implicitly casts them back to
1283 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
1284 * godawful API!) */
1285 assert_se(ungetc((unsigned char) c, f) != EOF);
1286 break;
1287 }
1288
1289 count++;
1290
1291 if (eol != EOL_NONE) {
1292 /* If we are on a tty, we can't shouldn't wait for more input, because that
1293 * generally means waiting for the user, interactively. In the case of a TTY
1294 * we expect only \n as the single EOL marker, so we are in the lucky
1295 * position that there is no need to wait. We check this condition last, to
1296 * avoid isatty() check if not necessary. */
1297
1298 if ((flags & (READ_LINE_IS_A_TTY|READ_LINE_NOT_A_TTY)) == 0) {
1299 int fd;
1300
1301 fd = fileno(f);
1302 if (fd < 0) /* Maybe an fmemopen() stream? Handle this gracefully,
1303 * and don't call isatty() on an invalid fd */
1304 flags |= READ_LINE_NOT_A_TTY;
1305 else
1306 flags |= isatty(fd) ? READ_LINE_IS_A_TTY : READ_LINE_NOT_A_TTY;
1307 }
1308 if (FLAGS_SET(flags, READ_LINE_IS_A_TTY))
1309 break;
1310 }
1311
1312 if (eol != EOL_NONE) {
1313 previous_eol |= eol;
1314 continue;
1315 }
1316
1317 if (ret) {
1318 if (!GREEDY_REALLOC(buffer, n + 2))
1319 return -ENOMEM;
1320
1321 buffer[n] = c;
1322 }
1323
1324 n++;
1325 }
1326 }
1327
1328 if (ret) {
1329 buffer[n] = 0;
1330
1331 *ret = TAKE_PTR(buffer);
1332 }
1333
1334 return (int) count;
1335 }
1336
1337 int safe_fgetc(FILE *f, char *ret) {
1338 int k;
1339
1340 assert(f);
1341
1342 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
1343 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
1344 * has. */
1345
1346 errno = 0;
1347 k = fgetc(f);
1348 if (k == EOF) {
1349 if (ferror(f))
1350 return errno_or_else(EIO);
1351
1352 if (ret)
1353 *ret = 0;
1354
1355 return 0;
1356 }
1357
1358 if (ret)
1359 *ret = k;
1360
1361 return 1;
1362 }
1363
1364 int warn_file_is_world_accessible(const char *filename, struct stat *st, const char *unit, unsigned line) {
1365 struct stat _st;
1366
1367 if (!filename)
1368 return 0;
1369
1370 if (!st) {
1371 if (stat(filename, &_st) < 0)
1372 return -errno;
1373 st = &_st;
1374 }
1375
1376 if ((st->st_mode & S_IRWXO) == 0)
1377 return 0;
1378
1379 if (unit)
1380 log_syntax(unit, LOG_WARNING, filename, line, 0,
1381 "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1382 filename, st->st_mode & 07777);
1383 else
1384 log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1385 filename, st->st_mode & 07777);
1386 return 0;
1387 }
1388
1389 int rename_and_apply_smack_floor_label(const char *from, const char *to) {
1390 int r = 0;
1391 if (rename(from, to) < 0)
1392 return -errno;
1393
1394 #if HAVE_SMACK_RUN_LABEL
1395 r = mac_smack_apply(to, SMACK_ATTR_ACCESS, SMACK_FLOOR_LABEL);
1396 if (r < 0)
1397 return r;
1398 #endif
1399 return r;
1400 }