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) {
61 needs_nl = !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) && !endswith(line, "\n");
63 if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) {
64 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
65 * that the write goes out in one go, instead of two */
67 line = strjoina(line, "\n");
71 if (fputs(line, f) == EOF)
75 if (fputc('\n', f) == EOF)
78 if (flags & WRITE_STRING_FILE_SYNC)
79 r = fflush_sync_and_check(f);
81 r = fflush_and_check(f);
86 struct timespec twice[2] = {*ts, *ts};
88 if (futimens(fileno(f), twice) < 0)
95 static int write_string_file_atomic(
98 WriteStringFileFlags flags,
99 struct timespec *ts) {
101 _cleanup_fclose_ FILE *f = NULL;
102 _cleanup_free_ char *p = NULL;
108 r = fopen_temporary(fn, &f, &p);
112 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
113 (void) fchmod_umask(fileno(f), 0644);
115 r = write_string_stream_ts(f, line, flags, ts);
119 if (rename(p, fn) < 0) {
131 int write_string_file_ts(
134 WriteStringFileFlags flags,
135 struct timespec *ts) {
137 _cleanup_fclose_ FILE *f = NULL;
143 /* We don't know how to verify whether the file contents was already on-disk. */
144 assert(!((flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE) && (flags & WRITE_STRING_FILE_SYNC)));
146 if (flags & WRITE_STRING_FILE_ATOMIC) {
147 assert(flags & WRITE_STRING_FILE_CREATE);
149 r = write_string_file_atomic(fn, line, flags, ts);
157 if (flags & WRITE_STRING_FILE_CREATE) {
166 /* We manually build our own version of fopen(..., "we") that
167 * works without O_CREAT */
168 fd = open(fn, O_WRONLY|O_CLOEXEC|O_NOCTTY);
174 f = fdopen(fd, "we");
182 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
184 if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
185 setvbuf(f, NULL, _IONBF, 0);
187 r = write_string_stream_ts(f, line, flags, ts);
194 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
199 /* OK, the operation failed, but let's see if the right
200 * contents in place already. If so, eat up the error. */
202 q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
209 int read_one_line_file(const char *fn, char **line) {
210 _cleanup_fclose_ FILE *f = NULL;
220 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
222 r = read_line(f, LONG_LINE_MAX, line);
223 return r < 0 ? r : 0;
226 int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
227 _cleanup_fclose_ FILE *f = NULL;
228 _cleanup_free_ char *buf = NULL;
236 if (accept_extra_nl && endswith(blob, "\n"))
237 accept_extra_nl = false;
239 buf = malloc(l + accept_extra_nl + 1);
247 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
249 /* We try to read one byte more than we need, so that we know whether we hit eof */
251 k = fread(buf, 1, l + accept_extra_nl + 1, f);
253 return errno > 0 ? -errno : -EIO;
255 if (k != l && k != l + accept_extra_nl)
257 if (memcmp(buf, blob, l) != 0)
259 if (k > l && buf[l] != '\n')
265 int read_full_stream(FILE *f, char **contents, size_t *size) {
266 _cleanup_free_ char *buf = NULL;
277 if (fd >= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
278 * optimize our buffering) */
280 if (fstat(fileno(f), &st) < 0)
283 if (S_ISREG(st.st_mode)) {
286 if (st.st_size > READ_FULL_BYTES_MAX)
289 /* Start with the right file size, but be prepared for files from /proc which generally report a file
290 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
291 * already makes us notice the EOF. */
302 t = realloc(buf, n + 1);
308 k = fread(buf + l, 1, n - l, f);
313 return errno > 0 ? -errno : -EIO;
318 /* We aren't expecting fread() to return a short read outside
319 * of (error && eof), assert buffer is full and enlarge buffer.
324 if (n >= READ_FULL_BYTES_MAX)
327 n = MIN(n * 2, READ_FULL_BYTES_MAX);
331 *contents = TAKE_PTR(buf);
339 int read_full_file(const char *fn, char **contents, size_t *size) {
340 _cleanup_fclose_ FILE *f = NULL;
349 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
351 return read_full_stream(f, contents, size);
354 static int parse_env_file_internal(
358 int (*push) (const char *filename, unsigned line,
359 const char *key, char *value, void *userdata, int *n_pushed),
363 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;
364 _cleanup_free_ char *contents = NULL, *key = NULL, *value = NULL;
376 SINGLE_QUOTE_VALUE_ESCAPE,
378 DOUBLE_QUOTE_VALUE_ESCAPE,
386 r = read_full_stream(f, &contents, NULL);
388 r = read_full_file(fname, &contents, NULL);
392 for (p = contents; *p; p++) {
398 if (strchr(COMMENTS, c))
400 else if (!strchr(WHITESPACE, c)) {
402 last_key_whitespace = (size_t) -1;
404 if (!GREEDY_REALLOC(key, key_alloc, n_key+2))
412 if (strchr(newline, c)) {
416 } else if (c == '=') {
418 last_value_whitespace = (size_t) -1;
420 if (!strchr(WHITESPACE, c))
421 last_key_whitespace = (size_t) -1;
422 else if (last_key_whitespace == (size_t) -1)
423 last_key_whitespace = n_key;
425 if (!GREEDY_REALLOC(key, key_alloc, n_key+2))
434 if (strchr(newline, c)) {
442 /* strip trailing whitespace from key */
443 if (last_key_whitespace != (size_t) -1)
444 key[last_key_whitespace] = 0;
446 r = push(fname, line, key, value, userdata, n_pushed);
452 value_alloc = n_value = 0;
454 } else if (c == '\'')
455 state = SINGLE_QUOTE_VALUE;
457 state = DOUBLE_QUOTE_VALUE;
459 state = VALUE_ESCAPE;
460 else if (!strchr(WHITESPACE, c)) {
463 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
466 value[n_value++] = c;
472 if (strchr(newline, c)) {
481 /* Chomp off trailing whitespace from value */
482 if (last_value_whitespace != (size_t) -1)
483 value[last_value_whitespace] = 0;
485 /* strip trailing whitespace from key */
486 if (last_key_whitespace != (size_t) -1)
487 key[last_key_whitespace] = 0;
489 r = push(fname, line, key, value, userdata, n_pushed);
495 value_alloc = n_value = 0;
497 } else if (c == '\\') {
498 state = VALUE_ESCAPE;
499 last_value_whitespace = (size_t) -1;
501 if (!strchr(WHITESPACE, c))
502 last_value_whitespace = (size_t) -1;
503 else if (last_value_whitespace == (size_t) -1)
504 last_value_whitespace = n_value;
506 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
509 value[n_value++] = c;
517 if (!strchr(newline, c)) {
518 /* Escaped newlines we eat up entirely */
519 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
522 value[n_value++] = c;
526 case SINGLE_QUOTE_VALUE:
530 state = SINGLE_QUOTE_VALUE_ESCAPE;
532 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
535 value[n_value++] = c;
540 case SINGLE_QUOTE_VALUE_ESCAPE:
541 state = SINGLE_QUOTE_VALUE;
543 if (!strchr(newline, c)) {
544 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
547 value[n_value++] = c;
551 case DOUBLE_QUOTE_VALUE:
555 state = DOUBLE_QUOTE_VALUE_ESCAPE;
557 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
560 value[n_value++] = c;
565 case DOUBLE_QUOTE_VALUE_ESCAPE:
566 state = DOUBLE_QUOTE_VALUE;
568 if (!strchr(newline, c)) {
569 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
572 value[n_value++] = c;
578 state = COMMENT_ESCAPE;
579 else if (strchr(newline, c)) {
596 SINGLE_QUOTE_VALUE_ESCAPE,
598 DOUBLE_QUOTE_VALUE_ESCAPE)) {
606 if (last_value_whitespace != (size_t) -1)
607 value[last_value_whitespace] = 0;
609 /* strip trailing whitespace from key */
610 if (last_key_whitespace != (size_t) -1)
611 key[last_key_whitespace] = 0;
613 r = push(fname, line, key, value, userdata, n_pushed);
623 static int check_utf8ness_and_warn(
624 const char *filename, unsigned line,
625 const char *key, char *value) {
627 if (!utf8_is_valid(key)) {
628 _cleanup_free_ char *p = NULL;
630 p = utf8_escape_invalid(key);
631 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p);
635 if (value && !utf8_is_valid(value)) {
636 _cleanup_free_ char *p = NULL;
638 p = utf8_escape_invalid(value);
639 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, p);
646 static int parse_env_file_push(
647 const char *filename, unsigned line,
648 const char *key, char *value,
653 va_list aq, *ap = userdata;
656 r = check_utf8ness_and_warn(filename, line, key, value);
662 while ((k = va_arg(aq, const char *))) {
665 v = va_arg(aq, char **);
698 r = parse_env_file_internal(f, fname, newline, parse_env_file_push, &aq, &n_pushed);
715 va_start(ap, newline);
716 r = parse_env_filev(f, fname, newline, ap);
722 #if 0 /// UNNEEDED by elogind
723 static int load_env_file_push(
724 const char *filename, unsigned line,
725 const char *key, char *value,
728 char ***m = userdata;
732 r = check_utf8ness_and_warn(filename, line, key, value);
736 p = strjoin(key, "=", value);
740 r = strv_env_replace(m, p);
753 int load_env_file(FILE *f, const char *fname, const char *newline, char ***rl) {
760 r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
771 static int load_env_file_push_pairs(
772 const char *filename, unsigned line,
773 const char *key, char *value,
776 char ***m = userdata;
779 r = check_utf8ness_and_warn(filename, line, key, value);
783 r = strv_extend(m, key);
788 r = strv_extend(m, "");
792 r = strv_push(m, value);
803 int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
810 r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
819 #if 0 /// UNNEEDED by elogind
821 static int merge_env_file_push(
822 const char *filename, unsigned line,
823 const char *key, char *value,
827 char ***env = userdata;
828 char *expanded_value;
833 log_error("%s:%u: invalid syntax (around \"%s\"), ignoring.", strna(filename), line, key);
837 if (!env_name_is_valid(key)) {
838 log_error("%s:%u: invalid variable name \"%s\", ignoring.", strna(filename), line, key);
843 expanded_value = replace_env(value, *env,
844 REPLACE_ENV_USE_ENVIRONMENT|
845 REPLACE_ENV_ALLOW_BRACELESS|
846 REPLACE_ENV_ALLOW_EXTENDED);
850 free_and_replace(value, expanded_value);
852 return load_env_file_push(filename, line, key, value, env, n_pushed);
860 /* NOTE: this function supports braceful and braceless variable expansions,
861 * plus "extended" substitutions, unlike other exported parsing functions.
864 return parse_env_file_internal(f, fname, NEWLINE, merge_env_file_push, env, NULL);
867 static void write_env_var(FILE *f, const char *v) {
873 fputs_unlocked(v, f);
874 fputc_unlocked('\n', f);
879 fwrite_unlocked(v, 1, p-v, f);
881 if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
882 fputc_unlocked('\"', f);
885 if (strchr(SHELL_NEED_ESCAPE, *p))
886 fputc_unlocked('\\', f);
888 fputc_unlocked(*p, f);
891 fputc_unlocked('\"', f);
893 fputs_unlocked(p, f);
895 fputc_unlocked('\n', f);
898 int write_env_file(const char *fname, char **l) {
899 _cleanup_fclose_ FILE *f = NULL;
900 _cleanup_free_ char *p = NULL;
906 r = fopen_temporary(fname, &f, &p);
910 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
911 (void) fchmod_umask(fileno(f), 0644);
914 write_env_var(f, *i);
916 r = fflush_and_check(f);
918 if (rename(p, fname) >= 0)
928 int executable_is_script(const char *path, char **interpreter) {
929 _cleanup_free_ char *line = NULL;
936 r = read_one_line_file(path, &line);
937 if (r == -ENOBUFS) /* First line overly long? if so, then it's not a script */
942 if (!startswith(line, "#!"))
945 ans = strstrip(line + 2);
946 len = strcspn(ans, " \t");
951 ans = strndup(ans, len);
961 * Retrieve one field from a file like /proc/self/status. pattern
962 * should not include whitespace or the delimiter (':'). pattern matches only
963 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
964 * zeros after the ':' will be skipped. field must be freed afterwards.
965 * terminator specifies the terminating characters of the field value (not
966 * included in the value).
968 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
969 _cleanup_free_ char *status = NULL;
979 r = read_full_file(filename, &status, NULL);
989 t = strstr(t, pattern);
993 /* Check that pattern occurs in beginning of line. */
994 pattern_ok = (t == status || t[-1] == '\n');
996 t += strlen(pattern);
998 } while (!pattern_ok);
1000 t += strspn(t, " \t");
1004 } while (*t != ':');
1009 t += strspn(t, " \t");
1011 /* Also skip zeros, because when this is used for
1012 * capabilities, we don't want the zeros. This way the
1013 * same capability set always maps to the same string,
1014 * irrespective of the total capability set size. For
1015 * other numbers it shouldn't matter. */
1016 t += strspn(t, "0");
1017 /* Back off one char if there's nothing but whitespace
1019 if (!*t || isspace(*t))
1023 len = strcspn(t, terminator);
1025 f = strndup(t, len);
1033 DIR *xopendirat(int fd, const char *name, int flags) {
1037 assert(!(flags & O_CREAT));
1039 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
1052 #if 0 /// UNNEEDED by elogind
1053 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
1060 if (!path_strv_resolve_uniq(search, root))
1063 STRV_FOREACH(i, search) {
1064 _cleanup_free_ char *p = NULL;
1068 p = strjoin(root, *i, "/", path);
1070 p = strjoin(*i, "/", path);
1080 if (errno != ENOENT)
1087 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
1088 _cleanup_strv_free_ char **copy = NULL;
1094 if (path_is_absolute(path)) {
1097 f = fopen(path, mode);
1106 copy = strv_copy((char**) search);
1110 return search_and_fopen_internal(path, mode, root, copy, _f);
1113 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
1114 _cleanup_strv_free_ char **s = NULL;
1116 if (path_is_absolute(path)) {
1119 f = fopen(path, mode);
1128 s = strv_split_nulstr(search);
1132 return search_and_fopen_internal(path, mode, root, s, _f);
1136 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1145 r = tempfn_xxxxxx(path, NULL, &t);
1149 fd = mkostemp_safe(t);
1155 f = fdopen(fd, "we");
1169 int fflush_and_check(FILE *f) {
1176 return errno > 0 ? -errno : -EIO;
1181 int fflush_sync_and_check(FILE *f) {
1186 r = fflush_and_check(f);
1190 if (fsync(fileno(f)) < 0)
1193 r = fsync_directory_of_file(fileno(f));
1200 /* This is much like mkostemp() but is subject to umask(). */
1201 int mkostemp_safe(char *pattern) {
1202 _cleanup_umask_ mode_t u = 0;
1209 fd = mkostemp(pattern, O_CLOEXEC);
1216 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1228 * /foo/bar/.#<extra>waldoXXXXXX
1232 if (!filename_is_valid(fn))
1235 extra = strempty(extra);
1237 t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1241 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1243 *ret = path_kill_slashes(t);
1247 int tempfn_random(const char *p, const char *extra, char **ret) {
1261 * /foo/bar/.#<extra>waldobaa2a261115984a9
1265 if (!filename_is_valid(fn))
1268 extra = strempty(extra);
1270 t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1274 x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1277 for (i = 0; i < 16; i++) {
1278 *(x++) = hexchar(u & 0xF);
1284 *ret = path_kill_slashes(t);
1288 #if 0 /// UNNEEDED by elogind
1289 int tempfn_random_child(const char *p, const char *extra, char **ret) {
1300 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1309 extra = strempty(extra);
1311 t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1315 x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
1318 for (i = 0; i < 16; i++) {
1319 *(x++) = hexchar(u & 0xF);
1325 *ret = path_kill_slashes(t);
1329 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1330 char ln[DECIMAL_STR_MAX(n)+2];
1332 /* Creates a "timestamp" file, that contains nothing but a
1333 * usec_t timestamp, formatted in ASCII. */
1335 if (n <= 0 || n >= USEC_INFINITY)
1338 xsprintf(ln, USEC_FMT "\n", n);
1340 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1343 int read_timestamp_file(const char *fn, usec_t *ret) {
1344 _cleanup_free_ char *ln = NULL;
1348 r = read_one_line_file(fn, &ln);
1352 r = safe_atou64(ln, &t);
1356 if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1363 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1368 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1369 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1370 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1371 * element, but not before the first one. */
1381 r = fputs(separator, f);
1393 int open_tmpfile_unlinkable(const char *directory, int flags) {
1398 r = tmp_dir(&directory);
1403 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1405 /* Try O_TMPFILE first, if it is supported */
1406 fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1410 /* Fall back to unguessable name + unlinking */
1411 p = strjoina(directory, "/systemd-tmp-XXXXXX");
1413 fd = mkostemp_safe(p);
1422 #if 0 /// UNNEEDED by elogind
1423 int open_tmpfile_linkable(const char *target, int flags, char **ret_path) {
1424 _cleanup_free_ char *tmp = NULL;
1430 /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1431 assert((flags & O_EXCL) == 0);
1433 /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1434 * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1435 * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1438 _cleanup_free_ char *dn = NULL;
1440 dn = dirname_malloc(target);
1444 fd = open(dn, O_TMPFILE|flags, 0640);
1450 log_debug_errno(errno, "Failed to use O_TMPFILE on %s: %m", dn);
1453 r = tempfn_random(target, NULL, &tmp);
1457 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640);
1461 *ret_path = TAKE_PTR(tmp);
1467 int open_serialization_fd(const char *ident) {
1470 fd = memfd_create(ident, MFD_CLOEXEC);
1474 path = getpid_cached() == 1 ? "/run/systemd" : "/tmp";
1475 fd = open_tmpfile_unlinkable(path, O_RDWR|O_CLOEXEC);
1479 log_debug("Serializing %s to %s.", ident, path);
1481 log_debug("Serializing %s to memfd.", ident);
1486 #if 0 /// UNNEEDED by elogind
1487 int link_tmpfile(int fd, const char *path, const char *target) {
1492 /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1493 * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1494 * on the directory, and renameat2() is used instead.
1496 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1497 * operation currently (renameat2() does), and there is no nice way to emulate this. */
1500 if (rename_noreplace(AT_FDCWD, path, AT_FDCWD, target) < 0)
1503 char proc_fd_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
1505 xsprintf(proc_fd_path, "/proc/self/fd/%i", fd);
1507 if (linkat(AT_FDCWD, proc_fd_path, AT_FDCWD, target, AT_SYMLINK_FOLLOW) < 0)
1514 int read_nul_string(FILE *f, char **ret) {
1515 _cleanup_free_ char *x = NULL;
1516 size_t allocated = 0, n = 0;
1521 /* Reads a NUL-terminated string from the specified file. */
1526 if (!GREEDY_REALLOC(x, allocated, n+2))
1530 if (c == 0) /* Terminate at NUL byte */
1535 break; /* Terminate at EOF */
1554 int mkdtemp_malloc(const char *template, char **ret) {
1560 p = strdup(template);
1574 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile);
1576 int read_line(FILE *f, size_t limit, char **ret) {
1577 _cleanup_free_ char *buffer = NULL;
1578 size_t n = 0, allocated = 0, count = 0;
1582 /* Something like a bounded version of getline().
1584 * Considers EOF, \n and \0 end of line delimiters, and does not include these delimiters in the string
1587 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1588 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1590 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1591 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1593 * If a line shall be skipped ret may be initialized as NULL. */
1596 if (!GREEDY_REALLOC(buffer, allocated, 1))
1601 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
1611 c = fgetc_unlocked(f);
1613 /* if we read an error, and have no data to return, then propagate the error */
1614 if (ferror_unlocked(f) && n == 0)
1615 return errno > 0 ? -errno : -EIO;
1622 if (IN_SET(c, '\n', 0)) /* Reached a delimiter */
1626 if (!GREEDY_REALLOC(buffer, allocated, n + 2))
1629 buffer[n] = (char) c;
1639 *ret = TAKE_PTR(buffer);