1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
13 #include <stdio_ext.h>
18 #include <sys/types.h>
21 #include "alloc-util.h"
29 #include "hexdecoct.h"
33 #include "parse-util.h"
34 #include "path-util.h"
35 #include "process-util.h"
36 #include "random-util.h"
37 #include "stdio-util.h"
38 #include "string-util.h"
40 //#include "time-util.h"
41 #include "umask-util.h"
44 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
46 int write_string_stream_ts(
49 WriteStringFileFlags flags,
50 struct timespec *ts) {
60 needs_nl = !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) && !endswith(line, "\n");
62 if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) {
63 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
64 * that the write goes out in one go, instead of two */
66 line = strjoina(line, "\n");
70 if (fputs(line, f) == EOF)
74 if (fputc('\n', f) == EOF)
78 struct timespec twice[2] = {*ts, *ts};
80 if (futimens(fileno(f), twice) < 0)
84 if (flags & WRITE_STRING_FILE_SYNC)
85 return fflush_sync_and_check(f);
87 return fflush_and_check(f);
90 static int write_string_file_atomic(
93 WriteStringFileFlags flags,
94 struct timespec *ts) {
96 _cleanup_fclose_ FILE *f = NULL;
97 _cleanup_free_ char *p = NULL;
103 r = fopen_temporary(fn, &f, &p);
107 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
108 (void) fchmod_umask(fileno(f), 0644);
110 r = write_string_stream_ts(f, line, flags, ts);
114 if (rename(p, fn) < 0) {
126 int write_string_file_ts(
129 WriteStringFileFlags flags,
130 struct timespec *ts) {
132 _cleanup_fclose_ FILE *f = NULL;
138 /* We don't know how to verify whether the file contents was already on-disk. */
139 assert(!((flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE) && (flags & WRITE_STRING_FILE_SYNC)));
141 if (flags & WRITE_STRING_FILE_ATOMIC) {
142 assert(flags & WRITE_STRING_FILE_CREATE);
144 r = write_string_file_atomic(fn, line, flags, ts);
152 if (flags & WRITE_STRING_FILE_CREATE) {
161 /* We manually build our own version of fopen(..., "we") that
162 * works without O_CREAT */
163 fd = open(fn, O_WRONLY|O_CLOEXEC|O_NOCTTY);
169 f = fdopen(fd, "we");
177 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
179 if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
180 setvbuf(f, NULL, _IONBF, 0);
182 r = write_string_stream_ts(f, line, flags, ts);
189 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
194 /* OK, the operation failed, but let's see if the right
195 * contents in place already. If so, eat up the error. */
197 q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
204 int read_one_line_file(const char *fn, char **line) {
205 _cleanup_fclose_ FILE *f = NULL;
215 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
217 r = read_line(f, LONG_LINE_MAX, line);
218 return r < 0 ? r : 0;
221 int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
222 _cleanup_fclose_ FILE *f = NULL;
223 _cleanup_free_ char *buf = NULL;
231 if (accept_extra_nl && endswith(blob, "\n"))
232 accept_extra_nl = false;
234 buf = malloc(l + accept_extra_nl + 1);
242 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
244 /* We try to read one byte more than we need, so that we know whether we hit eof */
246 k = fread(buf, 1, l + accept_extra_nl + 1, f);
248 return errno > 0 ? -errno : -EIO;
250 if (k != l && k != l + accept_extra_nl)
252 if (memcmp(buf, blob, l) != 0)
254 if (k > l && buf[l] != '\n')
260 int read_full_stream(FILE *f, char **contents, size_t *size) {
262 _cleanup_free_ char *buf = NULL;
268 if (fstat(fileno(f), &st) < 0)
273 if (S_ISREG(st.st_mode)) {
276 if (st.st_size > READ_FULL_BYTES_MAX)
279 /* Start with the right file size, but be prepared for files from /proc which generally report a file
280 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
281 * already makes us notice the EOF. */
291 t = realloc(buf, n + 1);
297 k = fread(buf + l, 1, n - l, f);
302 return errno > 0 ? -errno : -EIO;
307 /* We aren't expecting fread() to return a short read outside
308 * of (error && eof), assert buffer is full and enlarge buffer.
313 if (n >= READ_FULL_BYTES_MAX)
316 n = MIN(n * 2, READ_FULL_BYTES_MAX);
320 *contents = TAKE_PTR(buf);
328 int read_full_file(const char *fn, char **contents, size_t *size) {
329 _cleanup_fclose_ FILE *f = NULL;
338 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
340 return read_full_stream(f, contents, size);
343 static int parse_env_file_internal(
347 int (*push) (const char *filename, unsigned line,
348 const char *key, char *value, void *userdata, int *n_pushed),
352 size_t key_alloc = 0, n_key = 0, value_alloc = 0, n_value = 0, last_value_whitespace = (size_t) -1, last_key_whitespace = (size_t) -1;
353 _cleanup_free_ char *contents = NULL, *key = NULL, *value = NULL;
365 SINGLE_QUOTE_VALUE_ESCAPE,
367 DOUBLE_QUOTE_VALUE_ESCAPE,
375 r = read_full_stream(f, &contents, NULL);
377 r = read_full_file(fname, &contents, NULL);
381 for (p = contents; *p; p++) {
387 if (strchr(COMMENTS, c))
389 else if (!strchr(WHITESPACE, c)) {
391 last_key_whitespace = (size_t) -1;
393 if (!GREEDY_REALLOC(key, key_alloc, n_key+2))
401 if (strchr(newline, c)) {
405 } else if (c == '=') {
407 last_value_whitespace = (size_t) -1;
409 if (!strchr(WHITESPACE, c))
410 last_key_whitespace = (size_t) -1;
411 else if (last_key_whitespace == (size_t) -1)
412 last_key_whitespace = n_key;
414 if (!GREEDY_REALLOC(key, key_alloc, n_key+2))
423 if (strchr(newline, c)) {
431 /* strip trailing whitespace from key */
432 if (last_key_whitespace != (size_t) -1)
433 key[last_key_whitespace] = 0;
435 r = push(fname, line, key, value, userdata, n_pushed);
441 value_alloc = n_value = 0;
443 } else if (c == '\'')
444 state = SINGLE_QUOTE_VALUE;
446 state = DOUBLE_QUOTE_VALUE;
448 state = VALUE_ESCAPE;
449 else if (!strchr(WHITESPACE, c)) {
452 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
455 value[n_value++] = c;
461 if (strchr(newline, c)) {
470 /* Chomp off trailing whitespace from value */
471 if (last_value_whitespace != (size_t) -1)
472 value[last_value_whitespace] = 0;
474 /* strip trailing whitespace from key */
475 if (last_key_whitespace != (size_t) -1)
476 key[last_key_whitespace] = 0;
478 r = push(fname, line, key, value, userdata, n_pushed);
484 value_alloc = n_value = 0;
486 } else if (c == '\\') {
487 state = VALUE_ESCAPE;
488 last_value_whitespace = (size_t) -1;
490 if (!strchr(WHITESPACE, c))
491 last_value_whitespace = (size_t) -1;
492 else if (last_value_whitespace == (size_t) -1)
493 last_value_whitespace = n_value;
495 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
498 value[n_value++] = c;
506 if (!strchr(newline, c)) {
507 /* Escaped newlines we eat up entirely */
508 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
511 value[n_value++] = c;
515 case SINGLE_QUOTE_VALUE:
519 state = SINGLE_QUOTE_VALUE_ESCAPE;
521 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
524 value[n_value++] = c;
529 case SINGLE_QUOTE_VALUE_ESCAPE:
530 state = SINGLE_QUOTE_VALUE;
532 if (!strchr(newline, c)) {
533 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
536 value[n_value++] = c;
540 case DOUBLE_QUOTE_VALUE:
544 state = DOUBLE_QUOTE_VALUE_ESCAPE;
546 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
549 value[n_value++] = c;
554 case DOUBLE_QUOTE_VALUE_ESCAPE:
555 state = DOUBLE_QUOTE_VALUE;
557 if (!strchr(newline, c)) {
558 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
561 value[n_value++] = c;
567 state = COMMENT_ESCAPE;
568 else if (strchr(newline, c)) {
585 SINGLE_QUOTE_VALUE_ESCAPE,
587 DOUBLE_QUOTE_VALUE_ESCAPE)) {
595 if (last_value_whitespace != (size_t) -1)
596 value[last_value_whitespace] = 0;
598 /* strip trailing whitespace from key */
599 if (last_key_whitespace != (size_t) -1)
600 key[last_key_whitespace] = 0;
602 r = push(fname, line, key, value, userdata, n_pushed);
612 static int check_utf8ness_and_warn(
613 const char *filename, unsigned line,
614 const char *key, char *value) {
616 if (!utf8_is_valid(key)) {
617 _cleanup_free_ char *p = NULL;
619 p = utf8_escape_invalid(key);
620 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p);
624 if (value && !utf8_is_valid(value)) {
625 _cleanup_free_ char *p = NULL;
627 p = utf8_escape_invalid(value);
628 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, p);
635 static int parse_env_file_push(
636 const char *filename, unsigned line,
637 const char *key, char *value,
642 va_list aq, *ap = userdata;
645 r = check_utf8ness_and_warn(filename, line, key, value);
651 while ((k = va_arg(aq, const char *))) {
654 v = va_arg(aq, char **);
676 const char *newline, ...) {
684 va_start(ap, newline);
685 r = parse_env_file_internal(NULL, fname, newline, parse_env_file_push, &ap, &n_pushed);
688 return r < 0 ? r : n_pushed;
691 #if 0 /// UNNEEDED by elogind
692 static int load_env_file_push(
693 const char *filename, unsigned line,
694 const char *key, char *value,
697 char ***m = userdata;
701 r = check_utf8ness_and_warn(filename, line, key, value);
705 p = strjoin(key, "=", value);
709 r = strv_env_replace(m, p);
722 int load_env_file(FILE *f, const char *fname, const char *newline, char ***rl) {
729 r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
740 static int load_env_file_push_pairs(
741 const char *filename, unsigned line,
742 const char *key, char *value,
745 char ***m = userdata;
748 r = check_utf8ness_and_warn(filename, line, key, value);
752 r = strv_extend(m, key);
757 r = strv_extend(m, "");
761 r = strv_push(m, value);
772 int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
779 r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
788 #if 0 /// UNNEEDED by elogind
790 static int merge_env_file_push(
791 const char *filename, unsigned line,
792 const char *key, char *value,
796 char ***env = userdata;
797 char *expanded_value;
802 log_error("%s:%u: invalid syntax (around \"%s\"), ignoring.", strna(filename), line, key);
806 if (!env_name_is_valid(key)) {
807 log_error("%s:%u: invalid variable name \"%s\", ignoring.", strna(filename), line, key);
812 expanded_value = replace_env(value, *env,
813 REPLACE_ENV_USE_ENVIRONMENT|
814 REPLACE_ENV_ALLOW_BRACELESS|
815 REPLACE_ENV_ALLOW_EXTENDED);
819 free_and_replace(value, expanded_value);
821 return load_env_file_push(filename, line, key, value, env, n_pushed);
829 /* NOTE: this function supports braceful and braceless variable expansions,
830 * plus "extended" substitutions, unlike other exported parsing functions.
833 return parse_env_file_internal(f, fname, NEWLINE, merge_env_file_push, env, NULL);
836 static void write_env_var(FILE *f, const char *v) {
842 fputs_unlocked(v, f);
843 fputc_unlocked('\n', f);
848 fwrite_unlocked(v, 1, p-v, f);
850 if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
851 fputc_unlocked('\"', f);
854 if (strchr(SHELL_NEED_ESCAPE, *p))
855 fputc_unlocked('\\', f);
857 fputc_unlocked(*p, f);
860 fputc_unlocked('\"', f);
862 fputs_unlocked(p, f);
864 fputc_unlocked('\n', f);
867 int write_env_file(const char *fname, char **l) {
868 _cleanup_fclose_ FILE *f = NULL;
869 _cleanup_free_ char *p = NULL;
875 r = fopen_temporary(fname, &f, &p);
879 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
880 (void) fchmod_umask(fileno(f), 0644);
883 write_env_var(f, *i);
885 r = fflush_and_check(f);
887 if (rename(p, fname) >= 0)
897 int executable_is_script(const char *path, char **interpreter) {
898 _cleanup_free_ char *line = NULL;
905 r = read_one_line_file(path, &line);
906 if (r == -ENOBUFS) /* First line overly long? if so, then it's not a script */
911 if (!startswith(line, "#!"))
914 ans = strstrip(line + 2);
915 len = strcspn(ans, " \t");
920 ans = strndup(ans, len);
930 * Retrieve one field from a file like /proc/self/status. pattern
931 * should not include whitespace or the delimiter (':'). pattern matches only
932 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
933 * zeros after the ':' will be skipped. field must be freed afterwards.
934 * terminator specifies the terminating characters of the field value (not
935 * included in the value).
937 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
938 _cleanup_free_ char *status = NULL;
948 r = read_full_file(filename, &status, NULL);
958 t = strstr(t, pattern);
962 /* Check that pattern occurs in beginning of line. */
963 pattern_ok = (t == status || t[-1] == '\n');
965 t += strlen(pattern);
967 } while (!pattern_ok);
969 t += strspn(t, " \t");
978 t += strspn(t, " \t");
980 /* Also skip zeros, because when this is used for
981 * capabilities, we don't want the zeros. This way the
982 * same capability set always maps to the same string,
983 * irrespective of the total capability set size. For
984 * other numbers it shouldn't matter. */
986 /* Back off one char if there's nothing but whitespace
988 if (!*t || isspace(*t))
992 len = strcspn(t, terminator);
1002 DIR *xopendirat(int fd, const char *name, int flags) {
1006 assert(!(flags & O_CREAT));
1008 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
1021 #if 0 /// UNNEEDED by elogind
1022 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
1029 if (!path_strv_resolve_uniq(search, root))
1032 STRV_FOREACH(i, search) {
1033 _cleanup_free_ char *p = NULL;
1037 p = strjoin(root, *i, "/", path);
1039 p = strjoin(*i, "/", path);
1049 if (errno != ENOENT)
1056 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
1057 _cleanup_strv_free_ char **copy = NULL;
1063 if (path_is_absolute(path)) {
1066 f = fopen(path, mode);
1075 copy = strv_copy((char**) search);
1079 return search_and_fopen_internal(path, mode, root, copy, _f);
1082 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
1083 _cleanup_strv_free_ char **s = NULL;
1085 if (path_is_absolute(path)) {
1088 f = fopen(path, mode);
1097 s = strv_split_nulstr(search);
1101 return search_and_fopen_internal(path, mode, root, s, _f);
1105 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1114 r = tempfn_xxxxxx(path, NULL, &t);
1118 fd = mkostemp_safe(t);
1124 f = fdopen(fd, "we");
1138 int fflush_and_check(FILE *f) {
1145 return errno > 0 ? -errno : -EIO;
1150 int fflush_sync_and_check(FILE *f) {
1155 r = fflush_and_check(f);
1159 if (fsync(fileno(f)) < 0)
1162 r = fsync_directory_of_file(fileno(f));
1169 /* This is much like mkostemp() but is subject to umask(). */
1170 int mkostemp_safe(char *pattern) {
1171 _cleanup_umask_ mode_t u = 0;
1178 fd = mkostemp(pattern, O_CLOEXEC);
1185 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1197 * /foo/bar/.#<extra>waldoXXXXXX
1201 if (!filename_is_valid(fn))
1204 extra = strempty(extra);
1206 t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1210 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1212 *ret = path_kill_slashes(t);
1216 int tempfn_random(const char *p, const char *extra, char **ret) {
1230 * /foo/bar/.#<extra>waldobaa2a261115984a9
1234 if (!filename_is_valid(fn))
1237 extra = strempty(extra);
1239 t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1243 x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1246 for (i = 0; i < 16; i++) {
1247 *(x++) = hexchar(u & 0xF);
1253 *ret = path_kill_slashes(t);
1257 #if 0 /// UNNEEDED by elogind
1258 int tempfn_random_child(const char *p, const char *extra, char **ret) {
1269 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1278 extra = strempty(extra);
1280 t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1284 x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
1287 for (i = 0; i < 16; i++) {
1288 *(x++) = hexchar(u & 0xF);
1294 *ret = path_kill_slashes(t);
1298 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1299 char ln[DECIMAL_STR_MAX(n)+2];
1301 /* Creates a "timestamp" file, that contains nothing but a
1302 * usec_t timestamp, formatted in ASCII. */
1304 if (n <= 0 || n >= USEC_INFINITY)
1307 xsprintf(ln, USEC_FMT "\n", n);
1309 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1312 int read_timestamp_file(const char *fn, usec_t *ret) {
1313 _cleanup_free_ char *ln = NULL;
1317 r = read_one_line_file(fn, &ln);
1321 r = safe_atou64(ln, &t);
1325 if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1332 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1337 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1338 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1339 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1340 * element, but not before the first one. */
1350 r = fputs(separator, f);
1362 int open_tmpfile_unlinkable(const char *directory, int flags) {
1367 r = tmp_dir(&directory);
1372 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1374 /* Try O_TMPFILE first, if it is supported */
1375 fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1379 /* Fall back to unguessable name + unlinking */
1380 p = strjoina(directory, "/systemd-tmp-XXXXXX");
1382 fd = mkostemp_safe(p);
1391 #if 0 /// UNNEEDED by elogind
1392 int open_tmpfile_linkable(const char *target, int flags, char **ret_path) {
1393 _cleanup_free_ char *tmp = NULL;
1399 /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1400 assert((flags & O_EXCL) == 0);
1402 /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1403 * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1404 * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1407 _cleanup_free_ char *dn = NULL;
1409 dn = dirname_malloc(target);
1413 fd = open(dn, O_TMPFILE|flags, 0640);
1419 log_debug_errno(errno, "Failed to use O_TMPFILE on %s: %m", dn);
1422 r = tempfn_random(target, NULL, &tmp);
1426 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640);
1430 *ret_path = TAKE_PTR(tmp);
1436 int open_serialization_fd(const char *ident) {
1439 fd = memfd_create(ident, MFD_CLOEXEC);
1443 path = getpid_cached() == 1 ? "/run/systemd" : "/tmp";
1444 fd = open_tmpfile_unlinkable(path, O_RDWR|O_CLOEXEC);
1448 log_debug("Serializing %s to %s.", ident, path);
1450 log_debug("Serializing %s to memfd.", ident);
1455 #if 0 /// UNNEEDED by elogind
1456 int link_tmpfile(int fd, const char *path, const char *target) {
1461 /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1462 * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1463 * on the directory, and renameat2() is used instead.
1465 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1466 * operation currently (renameat2() does), and there is no nice way to emulate this. */
1469 if (rename_noreplace(AT_FDCWD, path, AT_FDCWD, target) < 0)
1472 char proc_fd_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
1474 xsprintf(proc_fd_path, "/proc/self/fd/%i", fd);
1476 if (linkat(AT_FDCWD, proc_fd_path, AT_FDCWD, target, AT_SYMLINK_FOLLOW) < 0)
1483 int read_nul_string(FILE *f, char **ret) {
1484 _cleanup_free_ char *x = NULL;
1485 size_t allocated = 0, n = 0;
1490 /* Reads a NUL-terminated string from the specified file. */
1495 if (!GREEDY_REALLOC(x, allocated, n+2))
1499 if (c == 0) /* Terminate at NUL byte */
1504 break; /* Terminate at EOF */
1523 int mkdtemp_malloc(const char *template, char **ret) {
1529 p = strdup(template);
1543 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile);
1545 int read_line(FILE *f, size_t limit, char **ret) {
1546 _cleanup_free_ char *buffer = NULL;
1547 size_t n = 0, allocated = 0, count = 0;
1551 /* Something like a bounded version of getline().
1553 * Considers EOF, \n and \0 end of line delimiters, and does not include these delimiters in the string
1556 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1557 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1559 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1560 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1562 * If a line shall be skipped ret may be initialized as NULL. */
1565 if (!GREEDY_REALLOC(buffer, allocated, 1))
1570 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
1580 c = fgetc_unlocked(f);
1582 /* if we read an error, and have no data to return, then propagate the error */
1583 if (ferror_unlocked(f) && n == 0)
1584 return errno > 0 ? -errno : -EIO;
1591 if (IN_SET(c, '\n', 0)) /* Reached a delimiter */
1595 if (!GREEDY_REALLOC(buffer, allocated, n + 2))
1598 buffer[n] = (char) c;
1608 *ret = TAKE_PTR(buffer);