]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/fileio.c
basic: change read_one_line_file() to return number of bytes read
[thirdparty/systemd.git] / src / basic / fileio.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
a5c32cff 2
8bdc9a90 3#include <ctype.h>
11c3a366
TA
4#include <errno.h>
5#include <fcntl.h>
6#include <limits.h>
7#include <stdarg.h>
8#include <stdint.h>
35bbbf85 9#include <stdio_ext.h>
11c3a366
TA
10#include <stdlib.h>
11#include <string.h>
12#include <sys/stat.h>
13#include <sys/types.h>
a5c32cff 14#include <unistd.h>
cda134ab 15
b5efdb8a 16#include "alloc-util.h"
3ffd4af2
LP
17#include "fd-util.h"
18#include "fileio.h"
f4f15635 19#include "fs-util.h"
93cc7779
TA
20#include "log.h"
21#include "macro.h"
1d9ed171 22#include "missing.h"
33d52ab9 23#include "parse-util.h"
0d39fa9c 24#include "path-util.h"
33d52ab9 25#include "stdio-util.h"
07630cea 26#include "string-util.h"
e4de7287 27#include "tmpfile-util.h"
a5c32cff 28
c2d11a63
VC
29#define READ_FULL_BYTES_MAX (4U*1024U*1024U)
30
b1837133
LP
31int write_string_stream_ts(
32 FILE *f,
33 const char *line,
34 WriteStringFileFlags flags,
35 struct timespec *ts) {
dacd6cee 36
91dc2bf7 37 bool needs_nl;
be83711c 38 int r;
91dc2bf7 39
717603e3
LP
40 assert(f);
41 assert(line);
42
ba8b8c9e
MG
43 if (ferror(f))
44 return -EIO;
45
91dc2bf7
LP
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
94d3b60f
MG
56 if (fputs(line, f) == EOF)
57 return -errno;
58
91dc2bf7 59 if (needs_nl)
94d3b60f
MG
60 if (fputc('\n', f) == EOF)
61 return -errno;
a5c32cff 62
be83711c
CL
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
39c38d77
ZJS
70 if (ts) {
71 struct timespec twice[2] = {*ts, *ts};
72
73 if (futimens(fileno(f), twice) < 0)
74 return -errno;
75 }
76
be83711c 77 return 0;
a5c32cff
HH
78}
79
2eabcc77
LP
80static int write_string_file_atomic(
81 const char *fn,
82 const char *line,
b1837133 83 WriteStringFileFlags flags,
2eabcc77
LP
84 struct timespec *ts) {
85
a5c32cff
HH
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
35bbbf85 97 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
0d39fa9c 98 (void) fchmod_umask(fileno(f), 0644);
a5c32cff 99
b1837133 100 r = write_string_stream_ts(f, line, flags, ts);
9dd1b1e8
LP
101 if (r < 0)
102 goto fail;
103
104 if (rename(p, fn) < 0) {
105 r = -errno;
106 goto fail;
a5c32cff
HH
107 }
108
9dd1b1e8 109 return 0;
a5c32cff 110
9dd1b1e8
LP
111fail:
112 (void) unlink(p);
a5c32cff
HH
113 return r;
114}
115
b1837133
LP
116int write_string_file_ts(
117 const char *fn,
118 const char *line,
119 WriteStringFileFlags flags,
120 struct timespec *ts) {
121
4c1fc3e4 122 _cleanup_fclose_ FILE *f = NULL;
eb3da901 123 int q, r;
4c1fc3e4
DM
124
125 assert(fn);
126 assert(line);
127
265710c2
AJ
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)));
0675e94a 130
4c1fc3e4
DM
131 if (flags & WRITE_STRING_FILE_ATOMIC) {
132 assert(flags & WRITE_STRING_FILE_CREATE);
133
b1837133 134 r = write_string_file_atomic(fn, line, flags, ts);
eb3da901
LP
135 if (r < 0)
136 goto fail;
137
138 return r;
39c38d77 139 } else
234519ae 140 assert(!ts);
4c1fc3e4
DM
141
142 if (flags & WRITE_STRING_FILE_CREATE) {
143 f = fopen(fn, "we");
eb3da901
LP
144 if (!f) {
145 r = -errno;
146 goto fail;
147 }
4c1fc3e4
DM
148 } else {
149 int fd;
150
151 /* We manually build our own version of fopen(..., "we") that
152 * works without O_CREAT */
835d18ba 153 fd = open(fn, O_WRONLY|O_CLOEXEC|O_NOCTTY | ((flags & WRITE_STRING_FILE_NOFOLLOW) ? O_NOFOLLOW : 0));
eb3da901
LP
154 if (fd < 0) {
155 r = -errno;
156 goto fail;
157 }
4c1fc3e4 158
e92aaed3 159 f = fdopen(fd, "w");
4c1fc3e4 160 if (!f) {
eb3da901 161 r = -errno;
4c1fc3e4 162 safe_close(fd);
eb3da901 163 goto fail;
4c1fc3e4
DM
164 }
165 }
166
35bbbf85
LP
167 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
168
12ec9c30
TSH
169 if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
170 setvbuf(f, NULL, _IONBF, 0);
171
b1837133 172 r = write_string_stream_ts(f, line, flags, ts);
eb3da901
LP
173 if (r < 0)
174 goto fail;
175
176 return 0;
177
178fail:
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;
4c1fc3e4
DM
192}
193
3130fca5
LP
194int 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
a5c32cff
HH
213int read_one_line_file(const char *fn, char **line) {
214 _cleanup_fclose_ FILE *f = NULL;
a5c32cff
HH
215
216 assert(fn);
217 assert(line);
218
219 f = fopen(fn, "re");
220 if (!f)
221 return -errno;
222
35bbbf85
LP
223 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
224
d6062e3b 225 return read_line(f, LONG_LINE_MAX, line);
a5c32cff
HH
226}
227
eb3da901
LP
228int 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;
15dee3f0 232
eb3da901
LP
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
35bbbf85
LP
249 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
250
eb3da901
LP
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;
15dee3f0 263
eb3da901 264 return 1;
15dee3f0
LP
265}
266
2d78717b
LP
267int read_full_stream(
268 FILE *f,
269 char **ret_contents,
270 size_t *ret_size) {
271
a5c32cff
HH
272 _cleanup_free_ char *buf = NULL;
273 struct stat st;
c4054ddf
LP
274 size_t n, l;
275 int fd;
a5c32cff 276
717603e3 277 assert(f);
2d78717b 278 assert(ret_contents);
a5c32cff 279
2d78717b 280 n = LINE_MAX; /* Start size */
a5c32cff 281
c4054ddf
LP
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) */
717603e3 285
c4054ddf
LP
286 if (fstat(fileno(f), &st) < 0)
287 return -errno;
288
289 if (S_ISREG(st.st_mode)) {
717603e3 290
c4054ddf
LP
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 }
717603e3 301 }
a5c32cff 302
717603e3 303 l = 0;
a5c32cff
HH
304 for (;;) {
305 char *t;
306 size_t k;
307
c2d11a63 308 t = realloc(buf, n + 1);
a5c32cff
HH
309 if (!t)
310 return -ENOMEM;
311
312 buf = t;
5a89faf0 313 errno = 0;
a5c32cff 314 k = fread(buf + l, 1, n - l, f);
c2d11a63
VC
315 if (k > 0)
316 l += k;
a5c32cff 317
c2d11a63 318 if (ferror(f))
5a89faf0 319 return errno > 0 ? -errno : -EIO;
a5c32cff 320
c2d11a63 321 if (feof(f))
a5c32cff 322 break;
a5c32cff 323
c2d11a63
VC
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);
a5c32cff
HH
328
329 /* Safety check */
c2d11a63 330 if (n >= READ_FULL_BYTES_MAX)
a5c32cff 331 return -E2BIG;
c2d11a63 332
82b103a7 333 n = MIN(n * 2, READ_FULL_BYTES_MAX);
a5c32cff
HH
334 }
335
2d78717b
LP
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
a5c32cff 345 buf[l] = 0;
2d78717b 346 *ret_contents = TAKE_PTR(buf);
a5c32cff 347
2d78717b
LP
348 if (ret_size)
349 *ret_size = l;
a5c32cff
HH
350
351 return 0;
352}
353
717603e3
LP
354int 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
35bbbf85
LP
364 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
365
717603e3
LP
366 return read_full_stream(f, contents, size);
367}
368
68fee104 369int executable_is_script(const char *path, char **interpreter) {
c8b32e11 370 _cleanup_free_ char *line = NULL;
99c61f6b 371 size_t len;
68fee104 372 char *ans;
99c61f6b 373 int r;
68fee104
ZJS
374
375 assert(path);
376
377 r = read_one_line_file(path, &line);
99c61f6b
LP
378 if (r == -ENOBUFS) /* First line overly long? if so, then it's not a script */
379 return 0;
68fee104
ZJS
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}
69ab8088
ZJS
399
400/**
0a7b53bd 401 * Retrieve one field from a file like /proc/self/status. pattern
c4cd1d4d
AK
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).
69ab8088 407 */
c4cd1d4d 408int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
69ab8088 409 _cleanup_free_ char *status = NULL;
90110825 410 char *t, *f;
69ab8088
ZJS
411 size_t len;
412 int r;
413
c4cd1d4d 414 assert(terminator);
69ab8088 415 assert(filename);
7ff7394d 416 assert(pattern);
69ab8088
ZJS
417 assert(field);
418
419 r = read_full_file(filename, &status, NULL);
420 if (r < 0)
421 return r;
422
c4cd1d4d
AK
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++;
69ab8088 447
4ec29144 448 if (*t) {
1e5413f7
ZJS
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");
4ec29144
ZJS
457 /* Back off one char if there's nothing but whitespace
458 and zeros */
1e5413f7 459 if (!*t || isspace(*t))
313cefa1 460 t--;
4ec29144 461 }
69ab8088 462
c4cd1d4d 463 len = strcspn(t, terminator);
69ab8088 464
90110825
LP
465 f = strndup(t, len);
466 if (!f)
69ab8088
ZJS
467 return -ENOMEM;
468
90110825 469 *field = f;
69ab8088
ZJS
470 return 0;
471}
0d39fa9c
LP
472
473DIR *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
492static 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)
605405c6 507 p = strjoin(root, *i, "/", path);
0d39fa9c 508 else
605405c6 509 p = strjoin(*i, "/", path);
0d39fa9c
LP
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
526int 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
552int 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
0d39fa9c
LP
574int fflush_and_check(FILE *f) {
575 assert(f);
576
577 errno = 0;
578 fflush(f);
579
580 if (ferror(f))
f5e5c28f 581 return errno > 0 ? -errno : -EIO;
0d39fa9c
LP
582
583 return 0;
584}
585
0675e94a
AJ
586int 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
8ac2f74f
LP
598 r = fsync_directory_of_file(fileno(f));
599 if (r < 0)
600 return r;
601
0675e94a
AJ
602 return 0;
603}
604
33d52ab9
LP
605int 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
619int 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}
d390f8ef
LP
638
639int 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}
03532f0a 667
838894b0
LP
668/* A bitmask of the EOL markers we know */
669typedef 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
41f11239
LP
676static 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
838894b0
LP
685 if (c == '\0')
686 return EOL_ZERO;
687
688 return EOL_NONE;
689}
690
57d6f700 691DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile);
f858e514 692
41f11239 693int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) {
4f9a66a3 694 size_t n = 0, allocated = 0, count = 0;
838894b0 695 _cleanup_free_ char *buffer = NULL;
03a7dbea 696 int r;
4f9a66a3
LP
697
698 assert(f);
699
700 /* Something like a bounded version of getline().
701 *
838894b0
LP
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
4f9a66a3
LP
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
f858e514 729 {
3f691417 730 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
838894b0 731 EndOfLineMarker previous_eol = EOL_NONE;
f858e514 732 flockfile(f);
4f9a66a3 733
f858e514 734 for (;;) {
838894b0 735 EndOfLineMarker eol;
03a7dbea 736 char c;
4f9a66a3 737
f858e514
ZJS
738 if (n >= limit)
739 return -ENOBUFS;
4f9a66a3 740
31fd02f0
LP
741 if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */
742 return -ENOBUFS;
743
03a7dbea
LP
744 r = safe_fgetc(f, &c);
745 if (r < 0)
746 return r;
91a306b8 747 if (r == 0) /* EOF is definitely EOL */
f858e514 748 break;
4f9a66a3 749
41f11239 750 eol = categorize_eol(c, flags);
838894b0
LP
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
517b7760
LP
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);
f858e514 765 break;
838894b0
LP
766 }
767
91a306b8
LP
768 count++;
769
838894b0
LP
770 if (eol != EOL_NONE) {
771 previous_eol |= eol;
772 continue;
773 }
4f9a66a3 774
f858e514
ZJS
775 if (ret) {
776 if (!GREEDY_REALLOC(buffer, allocated, n + 2))
777 return -ENOMEM;
4f9a66a3 778
03a7dbea 779 buffer[n] = c;
4f9a66a3
LP
780 }
781
f858e514 782 n++;
4f9a66a3 783 }
4f9a66a3
LP
784 }
785
4f9a66a3
LP
786 if (ret) {
787 buffer[n] = 0;
788
1cc6c93a 789 *ret = TAKE_PTR(buffer);
4f9a66a3
LP
790 }
791
792 return (int) count;
793}
285a9b27
LP
794
795int 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}