]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/fileio.c
Merge pull request #11357 from GiacintoCifelli/dbus_labels
[thirdparty/systemd.git] / src / basic / fileio.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <ctype.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <limits.h>
7 #include <stdarg.h>
8 #include <stdint.h>
9 #include <stdio_ext.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15
16 #include "alloc-util.h"
17 #include "fd-util.h"
18 #include "fileio.h"
19 #include "fs-util.h"
20 #include "log.h"
21 #include "macro.h"
22 #include "missing.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "stdio-util.h"
26 #include "string-util.h"
27 #include "tmpfile-util.h"
28
29 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
30
31 int write_string_stream_ts(
32 FILE *f,
33 const char *line,
34 WriteStringFileFlags flags,
35 struct timespec *ts) {
36
37 bool needs_nl;
38 int r;
39
40 assert(f);
41 assert(line);
42
43 if (ferror(f))
44 return -EIO;
45
46 needs_nl = !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) && !endswith(line, "\n");
47
48 if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) {
49 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
50 * that the write goes out in one go, instead of two */
51
52 line = strjoina(line, "\n");
53 needs_nl = false;
54 }
55
56 if (fputs(line, f) == EOF)
57 return -errno;
58
59 if (needs_nl)
60 if (fputc('\n', f) == EOF)
61 return -errno;
62
63 if (flags & WRITE_STRING_FILE_SYNC)
64 r = fflush_sync_and_check(f);
65 else
66 r = fflush_and_check(f);
67 if (r < 0)
68 return r;
69
70 if (ts) {
71 struct timespec twice[2] = {*ts, *ts};
72
73 if (futimens(fileno(f), twice) < 0)
74 return -errno;
75 }
76
77 return 0;
78 }
79
80 static int write_string_file_atomic(
81 const char *fn,
82 const char *line,
83 WriteStringFileFlags flags,
84 struct timespec *ts) {
85
86 _cleanup_fclose_ FILE *f = NULL;
87 _cleanup_free_ char *p = NULL;
88 int r;
89
90 assert(fn);
91 assert(line);
92
93 r = fopen_temporary(fn, &f, &p);
94 if (r < 0)
95 return r;
96
97 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
98 (void) fchmod_umask(fileno(f), 0644);
99
100 r = write_string_stream_ts(f, line, flags, ts);
101 if (r < 0)
102 goto fail;
103
104 if (rename(p, fn) < 0) {
105 r = -errno;
106 goto fail;
107 }
108
109 return 0;
110
111 fail:
112 (void) unlink(p);
113 return r;
114 }
115
116 int write_string_file_ts(
117 const char *fn,
118 const char *line,
119 WriteStringFileFlags flags,
120 struct timespec *ts) {
121
122 _cleanup_fclose_ FILE *f = NULL;
123 int q, r;
124
125 assert(fn);
126 assert(line);
127
128 /* We don't know how to verify whether the file contents was already on-disk. */
129 assert(!((flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE) && (flags & WRITE_STRING_FILE_SYNC)));
130
131 if (flags & WRITE_STRING_FILE_ATOMIC) {
132 assert(flags & WRITE_STRING_FILE_CREATE);
133
134 r = write_string_file_atomic(fn, line, flags, ts);
135 if (r < 0)
136 goto fail;
137
138 return r;
139 } else
140 assert(!ts);
141
142 if (flags & WRITE_STRING_FILE_CREATE) {
143 f = fopen(fn, "we");
144 if (!f) {
145 r = -errno;
146 goto fail;
147 }
148 } else {
149 int fd;
150
151 /* We manually build our own version of fopen(..., "we") that
152 * works without O_CREAT */
153 fd = open(fn, O_WRONLY|O_CLOEXEC|O_NOCTTY | ((flags & WRITE_STRING_FILE_NOFOLLOW) ? O_NOFOLLOW : 0));
154 if (fd < 0) {
155 r = -errno;
156 goto fail;
157 }
158
159 f = fdopen(fd, "w");
160 if (!f) {
161 r = -errno;
162 safe_close(fd);
163 goto fail;
164 }
165 }
166
167 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
168
169 if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
170 setvbuf(f, NULL, _IONBF, 0);
171
172 r = write_string_stream_ts(f, line, flags, ts);
173 if (r < 0)
174 goto fail;
175
176 return 0;
177
178 fail:
179 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
180 return r;
181
182 f = safe_fclose(f);
183
184 /* OK, the operation failed, but let's see if the right
185 * contents in place already. If so, eat up the error. */
186
187 q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
188 if (q <= 0)
189 return r;
190
191 return 0;
192 }
193
194 int write_string_filef(
195 const char *fn,
196 WriteStringFileFlags flags,
197 const char *format, ...) {
198
199 _cleanup_free_ char *p = NULL;
200 va_list ap;
201 int r;
202
203 va_start(ap, format);
204 r = vasprintf(&p, format, ap);
205 va_end(ap);
206
207 if (r < 0)
208 return -ENOMEM;
209
210 return write_string_file(fn, p, flags);
211 }
212
213 int read_one_line_file(const char *fn, char **line) {
214 _cleanup_fclose_ FILE *f = NULL;
215
216 assert(fn);
217 assert(line);
218
219 f = fopen(fn, "re");
220 if (!f)
221 return -errno;
222
223 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
224
225 return read_line(f, LONG_LINE_MAX, line);
226 }
227
228 int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
229 _cleanup_fclose_ FILE *f = NULL;
230 _cleanup_free_ char *buf = NULL;
231 size_t l, k;
232
233 assert(fn);
234 assert(blob);
235
236 l = strlen(blob);
237
238 if (accept_extra_nl && endswith(blob, "\n"))
239 accept_extra_nl = false;
240
241 buf = malloc(l + accept_extra_nl + 1);
242 if (!buf)
243 return -ENOMEM;
244
245 f = fopen(fn, "re");
246 if (!f)
247 return -errno;
248
249 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
250
251 /* We try to read one byte more than we need, so that we know whether we hit eof */
252 errno = 0;
253 k = fread(buf, 1, l + accept_extra_nl + 1, f);
254 if (ferror(f))
255 return errno > 0 ? -errno : -EIO;
256
257 if (k != l && k != l + accept_extra_nl)
258 return 0;
259 if (memcmp(buf, blob, l) != 0)
260 return 0;
261 if (k > l && buf[l] != '\n')
262 return 0;
263
264 return 1;
265 }
266
267 int read_full_stream(
268 FILE *f,
269 char **ret_contents,
270 size_t *ret_size) {
271
272 _cleanup_free_ char *buf = NULL;
273 struct stat st;
274 size_t n, l;
275 int fd;
276
277 assert(f);
278 assert(ret_contents);
279
280 n = LINE_MAX; /* Start size */
281
282 fd = fileno(f);
283 if (fd >= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
284 * optimize our buffering) */
285
286 if (fstat(fileno(f), &st) < 0)
287 return -errno;
288
289 if (S_ISREG(st.st_mode)) {
290
291 /* Safety check */
292 if (st.st_size > READ_FULL_BYTES_MAX)
293 return -E2BIG;
294
295 /* Start with the right file size, but be prepared for files from /proc which generally report a file
296 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
297 * already makes us notice the EOF. */
298 if (st.st_size > 0)
299 n = st.st_size + 1;
300 }
301 }
302
303 l = 0;
304 for (;;) {
305 char *t;
306 size_t k;
307
308 t = realloc(buf, n + 1);
309 if (!t)
310 return -ENOMEM;
311
312 buf = t;
313 errno = 0;
314 k = fread(buf + l, 1, n - l, f);
315 if (k > 0)
316 l += k;
317
318 if (ferror(f))
319 return errno > 0 ? -errno : -EIO;
320
321 if (feof(f))
322 break;
323
324 /* We aren't expecting fread() to return a short read outside
325 * of (error && eof), assert buffer is full and enlarge buffer.
326 */
327 assert(l == n);
328
329 /* Safety check */
330 if (n >= READ_FULL_BYTES_MAX)
331 return -E2BIG;
332
333 n = MIN(n * 2, READ_FULL_BYTES_MAX);
334 }
335
336 if (!ret_size) {
337 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
338 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
339 * there'd be ambiguity about what we just read. */
340
341 if (memchr(buf, 0, l))
342 return -EBADMSG;
343 }
344
345 buf[l] = 0;
346 *ret_contents = TAKE_PTR(buf);
347
348 if (ret_size)
349 *ret_size = l;
350
351 return 0;
352 }
353
354 int read_full_file(const char *fn, char **contents, size_t *size) {
355 _cleanup_fclose_ FILE *f = NULL;
356
357 assert(fn);
358 assert(contents);
359
360 f = fopen(fn, "re");
361 if (!f)
362 return -errno;
363
364 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
365
366 return read_full_stream(f, contents, size);
367 }
368
369 int executable_is_script(const char *path, char **interpreter) {
370 _cleanup_free_ char *line = NULL;
371 size_t len;
372 char *ans;
373 int r;
374
375 assert(path);
376
377 r = read_one_line_file(path, &line);
378 if (r == -ENOBUFS) /* First line overly long? if so, then it's not a script */
379 return 0;
380 if (r < 0)
381 return r;
382
383 if (!startswith(line, "#!"))
384 return 0;
385
386 ans = strstrip(line + 2);
387 len = strcspn(ans, " \t");
388
389 if (len == 0)
390 return 0;
391
392 ans = strndup(ans, len);
393 if (!ans)
394 return -ENOMEM;
395
396 *interpreter = ans;
397 return 1;
398 }
399
400 /**
401 * Retrieve one field from a file like /proc/self/status. pattern
402 * should not include whitespace or the delimiter (':'). pattern matches only
403 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
404 * zeros after the ':' will be skipped. field must be freed afterwards.
405 * terminator specifies the terminating characters of the field value (not
406 * included in the value).
407 */
408 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
409 _cleanup_free_ char *status = NULL;
410 char *t, *f;
411 size_t len;
412 int r;
413
414 assert(terminator);
415 assert(filename);
416 assert(pattern);
417 assert(field);
418
419 r = read_full_file(filename, &status, NULL);
420 if (r < 0)
421 return r;
422
423 t = status;
424
425 do {
426 bool pattern_ok;
427
428 do {
429 t = strstr(t, pattern);
430 if (!t)
431 return -ENOENT;
432
433 /* Check that pattern occurs in beginning of line. */
434 pattern_ok = (t == status || t[-1] == '\n');
435
436 t += strlen(pattern);
437
438 } while (!pattern_ok);
439
440 t += strspn(t, " \t");
441 if (!*t)
442 return -ENOENT;
443
444 } while (*t != ':');
445
446 t++;
447
448 if (*t) {
449 t += strspn(t, " \t");
450
451 /* Also skip zeros, because when this is used for
452 * capabilities, we don't want the zeros. This way the
453 * same capability set always maps to the same string,
454 * irrespective of the total capability set size. For
455 * other numbers it shouldn't matter. */
456 t += strspn(t, "0");
457 /* Back off one char if there's nothing but whitespace
458 and zeros */
459 if (!*t || isspace(*t))
460 t--;
461 }
462
463 len = strcspn(t, terminator);
464
465 f = strndup(t, len);
466 if (!f)
467 return -ENOMEM;
468
469 *field = f;
470 return 0;
471 }
472
473 DIR *xopendirat(int fd, const char *name, int flags) {
474 int nfd;
475 DIR *d;
476
477 assert(!(flags & O_CREAT));
478
479 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
480 if (nfd < 0)
481 return NULL;
482
483 d = fdopendir(nfd);
484 if (!d) {
485 safe_close(nfd);
486 return NULL;
487 }
488
489 return d;
490 }
491
492 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
493 char **i;
494
495 assert(path);
496 assert(mode);
497 assert(_f);
498
499 if (!path_strv_resolve_uniq(search, root))
500 return -ENOMEM;
501
502 STRV_FOREACH(i, search) {
503 _cleanup_free_ char *p = NULL;
504 FILE *f;
505
506 if (root)
507 p = strjoin(root, *i, "/", path);
508 else
509 p = strjoin(*i, "/", path);
510 if (!p)
511 return -ENOMEM;
512
513 f = fopen(p, mode);
514 if (f) {
515 *_f = f;
516 return 0;
517 }
518
519 if (errno != ENOENT)
520 return -errno;
521 }
522
523 return -ENOENT;
524 }
525
526 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
527 _cleanup_strv_free_ char **copy = NULL;
528
529 assert(path);
530 assert(mode);
531 assert(_f);
532
533 if (path_is_absolute(path)) {
534 FILE *f;
535
536 f = fopen(path, mode);
537 if (f) {
538 *_f = f;
539 return 0;
540 }
541
542 return -errno;
543 }
544
545 copy = strv_copy((char**) search);
546 if (!copy)
547 return -ENOMEM;
548
549 return search_and_fopen_internal(path, mode, root, copy, _f);
550 }
551
552 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
553 _cleanup_strv_free_ char **s = NULL;
554
555 if (path_is_absolute(path)) {
556 FILE *f;
557
558 f = fopen(path, mode);
559 if (f) {
560 *_f = f;
561 return 0;
562 }
563
564 return -errno;
565 }
566
567 s = strv_split_nulstr(search);
568 if (!s)
569 return -ENOMEM;
570
571 return search_and_fopen_internal(path, mode, root, s, _f);
572 }
573
574 int fflush_and_check(FILE *f) {
575 assert(f);
576
577 errno = 0;
578 fflush(f);
579
580 if (ferror(f))
581 return errno > 0 ? -errno : -EIO;
582
583 return 0;
584 }
585
586 int fflush_sync_and_check(FILE *f) {
587 int r;
588
589 assert(f);
590
591 r = fflush_and_check(f);
592 if (r < 0)
593 return r;
594
595 if (fsync(fileno(f)) < 0)
596 return -errno;
597
598 r = fsync_directory_of_file(fileno(f));
599 if (r < 0)
600 return r;
601
602 return 0;
603 }
604
605 int write_timestamp_file_atomic(const char *fn, usec_t n) {
606 char ln[DECIMAL_STR_MAX(n)+2];
607
608 /* Creates a "timestamp" file, that contains nothing but a
609 * usec_t timestamp, formatted in ASCII. */
610
611 if (n <= 0 || n >= USEC_INFINITY)
612 return -ERANGE;
613
614 xsprintf(ln, USEC_FMT "\n", n);
615
616 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
617 }
618
619 int read_timestamp_file(const char *fn, usec_t *ret) {
620 _cleanup_free_ char *ln = NULL;
621 uint64_t t;
622 int r;
623
624 r = read_one_line_file(fn, &ln);
625 if (r < 0)
626 return r;
627
628 r = safe_atou64(ln, &t);
629 if (r < 0)
630 return r;
631
632 if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
633 return -ERANGE;
634
635 *ret = (usec_t) t;
636 return 0;
637 }
638
639 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
640 int r;
641
642 assert(s);
643
644 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
645 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
646 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
647 * element, but not before the first one. */
648
649 if (!f)
650 f = stdout;
651
652 if (space) {
653 if (!separator)
654 separator = " ";
655
656 if (*space) {
657 r = fputs(separator, f);
658 if (r < 0)
659 return r;
660 }
661
662 *space = true;
663 }
664
665 return fputs(s, f);
666 }
667
668 /* A bitmask of the EOL markers we know */
669 typedef enum EndOfLineMarker {
670 EOL_NONE = 0,
671 EOL_ZERO = 1 << 0, /* \0 (aka NUL) */
672 EOL_TEN = 1 << 1, /* \n (aka NL, aka LF) */
673 EOL_THIRTEEN = 1 << 2, /* \r (aka CR) */
674 } EndOfLineMarker;
675
676 static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) {
677
678 if (!IN_SET(flags, READ_LINE_ONLY_NUL)) {
679 if (c == '\n')
680 return EOL_TEN;
681 if (c == '\r')
682 return EOL_THIRTEEN;
683 }
684
685 if (c == '\0')
686 return EOL_ZERO;
687
688 return EOL_NONE;
689 }
690
691 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile);
692
693 int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) {
694 size_t n = 0, allocated = 0, count = 0;
695 _cleanup_free_ char *buffer = NULL;
696 int r;
697
698 assert(f);
699
700 /* Something like a bounded version of getline().
701 *
702 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
703 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
704 * endings:
705 *
706 * • \n (UNIX)
707 * • \r (old MacOS)
708 * • \0 (C strings)
709 * • \n\0
710 * • \r\0
711 * • \r\n (Windows)
712 * • \n\r
713 * • \r\n\0
714 * • \n\r\0
715 *
716 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
717 * the number of characters in the returned string). When EOF is hit, 0 is returned.
718 *
719 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
720 * delimiters. If the limit is hit we fail and return -ENOBUFS.
721 *
722 * If a line shall be skipped ret may be initialized as NULL. */
723
724 if (ret) {
725 if (!GREEDY_REALLOC(buffer, allocated, 1))
726 return -ENOMEM;
727 }
728
729 {
730 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
731 EndOfLineMarker previous_eol = EOL_NONE;
732 flockfile(f);
733
734 for (;;) {
735 EndOfLineMarker eol;
736 char c;
737
738 if (n >= limit)
739 return -ENOBUFS;
740
741 if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */
742 return -ENOBUFS;
743
744 r = safe_fgetc(f, &c);
745 if (r < 0)
746 return r;
747 if (r == 0) /* EOF is definitely EOL */
748 break;
749
750 eol = categorize_eol(c, flags);
751
752 if (FLAGS_SET(previous_eol, EOL_ZERO) ||
753 (eol == EOL_NONE && previous_eol != EOL_NONE) ||
754 (eol != EOL_NONE && (previous_eol & eol) != 0)) {
755 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
756 * EOL marker has been seen right before? In either of these three cases we are
757 * done. But first, let's put this character back in the queue. (Note that we have to
758 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
759 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
760 * pass a negative value here. That said, to complicate things further ungetc() is
761 * actually happy with most negative characters and implicitly casts them back to
762 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
763 * godawful API!) */
764 assert_se(ungetc((unsigned char) c, f) != EOF);
765 break;
766 }
767
768 count++;
769
770 if (eol != EOL_NONE) {
771 previous_eol |= eol;
772 continue;
773 }
774
775 if (ret) {
776 if (!GREEDY_REALLOC(buffer, allocated, n + 2))
777 return -ENOMEM;
778
779 buffer[n] = c;
780 }
781
782 n++;
783 }
784 }
785
786 if (ret) {
787 buffer[n] = 0;
788
789 *ret = TAKE_PTR(buffer);
790 }
791
792 return (int) count;
793 }
794
795 int safe_fgetc(FILE *f, char *ret) {
796 int k;
797
798 assert(f);
799
800 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
801 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
802 * has. */
803
804 errno = 0;
805 k = fgetc(f);
806 if (k == EOF) {
807 if (ferror(f))
808 return errno > 0 ? -errno : -EIO;
809
810 if (ret)
811 *ret = 0;
812
813 return 0;
814 }
815
816 if (ret)
817 *ret = k;
818
819 return 1;
820 }