1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2010 Lennart Poettering
11 #include <stdio_ext.h>
16 #include <sys/types.h>
19 #include "alloc-util.h"
27 #include "hexdecoct.h"
31 #include "parse-util.h"
32 #include "path-util.h"
33 #include "process-util.h"
34 #include "random-util.h"
35 #include "stdio-util.h"
36 #include "string-util.h"
38 //#include "time-util.h"
39 #include "umask-util.h"
42 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
44 int write_string_stream_ts(
47 WriteStringFileFlags flags,
48 struct timespec *ts) {
59 needs_nl = !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) && !endswith(line, "\n");
61 if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) {
62 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
63 * that the write goes out in one go, instead of two */
65 line = strjoina(line, "\n");
69 if (fputs(line, f) == EOF)
73 if (fputc('\n', f) == EOF)
76 if (flags & WRITE_STRING_FILE_SYNC)
77 r = fflush_sync_and_check(f);
79 r = fflush_and_check(f);
84 struct timespec twice[2] = {*ts, *ts};
86 if (futimens(fileno(f), twice) < 0)
93 static int write_string_file_atomic(
96 WriteStringFileFlags flags,
97 struct timespec *ts) {
99 _cleanup_fclose_ FILE *f = NULL;
100 _cleanup_free_ char *p = NULL;
106 r = fopen_temporary(fn, &f, &p);
110 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
111 (void) fchmod_umask(fileno(f), 0644);
113 r = write_string_stream_ts(f, line, flags, ts);
117 if (rename(p, fn) < 0) {
129 int write_string_file_ts(
132 WriteStringFileFlags flags,
133 struct timespec *ts) {
135 _cleanup_fclose_ FILE *f = NULL;
141 /* We don't know how to verify whether the file contents was already on-disk. */
142 assert(!((flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE) && (flags & WRITE_STRING_FILE_SYNC)));
144 if (flags & WRITE_STRING_FILE_ATOMIC) {
145 assert(flags & WRITE_STRING_FILE_CREATE);
147 r = write_string_file_atomic(fn, line, flags, ts);
155 if (flags & WRITE_STRING_FILE_CREATE) {
164 /* We manually build our own version of fopen(..., "we") that
165 * works without O_CREAT */
166 fd = open(fn, O_WRONLY|O_CLOEXEC|O_NOCTTY);
172 f = fdopen(fd, "we");
180 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
182 if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
183 setvbuf(f, NULL, _IONBF, 0);
185 r = write_string_stream_ts(f, line, flags, ts);
192 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
197 /* OK, the operation failed, but let's see if the right
198 * contents in place already. If so, eat up the error. */
200 q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
207 int write_string_filef(
209 WriteStringFileFlags flags,
210 const char *format, ...) {
212 _cleanup_free_ char *p = NULL;
216 va_start(ap, format);
217 r = vasprintf(&p, format, ap);
223 return write_string_file(fn, p, flags);
226 int read_one_line_file(const char *fn, char **line) {
227 _cleanup_fclose_ FILE *f = NULL;
237 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
239 r = read_line(f, LONG_LINE_MAX, line);
240 return r < 0 ? r : 0;
243 int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
244 _cleanup_fclose_ FILE *f = NULL;
245 _cleanup_free_ char *buf = NULL;
253 if (accept_extra_nl && endswith(blob, "\n"))
254 accept_extra_nl = false;
256 buf = malloc(l + accept_extra_nl + 1);
264 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
266 /* We try to read one byte more than we need, so that we know whether we hit eof */
268 k = fread(buf, 1, l + accept_extra_nl + 1, f);
270 return errno > 0 ? -errno : -EIO;
272 if (k != l && k != l + accept_extra_nl)
274 if (memcmp(buf, blob, l) != 0)
276 if (k > l && buf[l] != '\n')
282 int read_full_stream(FILE *f, char **contents, size_t *size) {
283 _cleanup_free_ char *buf = NULL;
294 if (fd >= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
295 * optimize our buffering) */
297 if (fstat(fileno(f), &st) < 0)
300 if (S_ISREG(st.st_mode)) {
303 if (st.st_size > READ_FULL_BYTES_MAX)
306 /* Start with the right file size, but be prepared for files from /proc which generally report a file
307 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
308 * already makes us notice the EOF. */
319 t = realloc(buf, n + 1);
325 k = fread(buf + l, 1, n - l, f);
330 return errno > 0 ? -errno : -EIO;
335 /* We aren't expecting fread() to return a short read outside
336 * of (error && eof), assert buffer is full and enlarge buffer.
341 if (n >= READ_FULL_BYTES_MAX)
344 n = MIN(n * 2, READ_FULL_BYTES_MAX);
348 *contents = TAKE_PTR(buf);
356 int read_full_file(const char *fn, char **contents, size_t *size) {
357 _cleanup_fclose_ FILE *f = NULL;
366 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
368 return read_full_stream(f, contents, size);
371 static int parse_env_file_internal(
375 int (*push) (const char *filename, unsigned line,
376 const char *key, char *value, void *userdata, int *n_pushed),
380 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;
381 _cleanup_free_ char *contents = NULL, *key = NULL, *value = NULL;
393 SINGLE_QUOTE_VALUE_ESCAPE,
395 DOUBLE_QUOTE_VALUE_ESCAPE,
403 r = read_full_stream(f, &contents, NULL);
405 r = read_full_file(fname, &contents, NULL);
409 for (p = contents; *p; p++) {
415 if (strchr(COMMENTS, c))
417 else if (!strchr(WHITESPACE, c)) {
419 last_key_whitespace = (size_t) -1;
421 if (!GREEDY_REALLOC(key, key_alloc, n_key+2))
429 if (strchr(newline, c)) {
433 } else if (c == '=') {
435 last_value_whitespace = (size_t) -1;
437 if (!strchr(WHITESPACE, c))
438 last_key_whitespace = (size_t) -1;
439 else if (last_key_whitespace == (size_t) -1)
440 last_key_whitespace = n_key;
442 if (!GREEDY_REALLOC(key, key_alloc, n_key+2))
451 if (strchr(newline, c)) {
459 /* strip trailing whitespace from key */
460 if (last_key_whitespace != (size_t) -1)
461 key[last_key_whitespace] = 0;
463 r = push(fname, line, key, value, userdata, n_pushed);
469 value_alloc = n_value = 0;
471 } else if (c == '\'')
472 state = SINGLE_QUOTE_VALUE;
474 state = DOUBLE_QUOTE_VALUE;
476 state = VALUE_ESCAPE;
477 else if (!strchr(WHITESPACE, c)) {
480 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
483 value[n_value++] = c;
489 if (strchr(newline, c)) {
498 /* Chomp off trailing whitespace from value */
499 if (last_value_whitespace != (size_t) -1)
500 value[last_value_whitespace] = 0;
502 /* strip trailing whitespace from key */
503 if (last_key_whitespace != (size_t) -1)
504 key[last_key_whitespace] = 0;
506 r = push(fname, line, key, value, userdata, n_pushed);
512 value_alloc = n_value = 0;
514 } else if (c == '\\') {
515 state = VALUE_ESCAPE;
516 last_value_whitespace = (size_t) -1;
518 if (!strchr(WHITESPACE, c))
519 last_value_whitespace = (size_t) -1;
520 else if (last_value_whitespace == (size_t) -1)
521 last_value_whitespace = n_value;
523 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
526 value[n_value++] = c;
534 if (!strchr(newline, c)) {
535 /* Escaped newlines we eat up entirely */
536 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
539 value[n_value++] = c;
543 case SINGLE_QUOTE_VALUE:
547 state = SINGLE_QUOTE_VALUE_ESCAPE;
549 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
552 value[n_value++] = c;
557 case SINGLE_QUOTE_VALUE_ESCAPE:
558 state = SINGLE_QUOTE_VALUE;
560 if (!strchr(newline, c)) {
561 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
564 value[n_value++] = c;
568 case DOUBLE_QUOTE_VALUE:
572 state = DOUBLE_QUOTE_VALUE_ESCAPE;
574 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
577 value[n_value++] = c;
582 case DOUBLE_QUOTE_VALUE_ESCAPE:
583 state = DOUBLE_QUOTE_VALUE;
585 if (!strchr(newline, c)) {
586 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
589 value[n_value++] = c;
595 state = COMMENT_ESCAPE;
596 else if (strchr(newline, c)) {
613 SINGLE_QUOTE_VALUE_ESCAPE,
615 DOUBLE_QUOTE_VALUE_ESCAPE)) {
623 if (last_value_whitespace != (size_t) -1)
624 value[last_value_whitespace] = 0;
626 /* strip trailing whitespace from key */
627 if (last_key_whitespace != (size_t) -1)
628 key[last_key_whitespace] = 0;
630 r = push(fname, line, key, value, userdata, n_pushed);
640 static int check_utf8ness_and_warn(
641 const char *filename, unsigned line,
642 const char *key, char *value) {
644 if (!utf8_is_valid(key)) {
645 _cleanup_free_ char *p = NULL;
647 p = utf8_escape_invalid(key);
648 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p);
652 if (value && !utf8_is_valid(value)) {
653 _cleanup_free_ char *p = NULL;
655 p = utf8_escape_invalid(value);
656 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, p);
663 static int parse_env_file_push(
664 const char *filename, unsigned line,
665 const char *key, char *value,
670 va_list aq, *ap = userdata;
673 r = check_utf8ness_and_warn(filename, line, key, value);
679 while ((k = va_arg(aq, const char *))) {
682 v = va_arg(aq, char **);
715 r = parse_env_file_internal(f, fname, newline, parse_env_file_push, &aq, &n_pushed);
732 va_start(ap, newline);
733 r = parse_env_filev(f, fname, newline, ap);
739 #if 0 /// UNNEEDED by elogind
740 static int load_env_file_push(
741 const char *filename, unsigned line,
742 const char *key, char *value,
745 char ***m = userdata;
749 r = check_utf8ness_and_warn(filename, line, key, value);
753 p = strjoin(key, "=", value);
757 r = strv_env_replace(m, p);
770 int load_env_file(FILE *f, const char *fname, const char *newline, char ***rl) {
777 r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
788 static int load_env_file_push_pairs(
789 const char *filename, unsigned line,
790 const char *key, char *value,
793 char ***m = userdata;
796 r = check_utf8ness_and_warn(filename, line, key, value);
800 r = strv_extend(m, key);
805 r = strv_extend(m, "");
809 r = strv_push(m, value);
820 int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
827 r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
836 #if 0 /// UNNEEDED by elogind
838 static int merge_env_file_push(
839 const char *filename, unsigned line,
840 const char *key, char *value,
844 char ***env = userdata;
845 char *expanded_value;
850 log_error("%s:%u: invalid syntax (around \"%s\"), ignoring.", strna(filename), line, key);
854 if (!env_name_is_valid(key)) {
855 log_error("%s:%u: invalid variable name \"%s\", ignoring.", strna(filename), line, key);
860 expanded_value = replace_env(value, *env,
861 REPLACE_ENV_USE_ENVIRONMENT|
862 REPLACE_ENV_ALLOW_BRACELESS|
863 REPLACE_ENV_ALLOW_EXTENDED);
867 free_and_replace(value, expanded_value);
869 return load_env_file_push(filename, line, key, value, env, n_pushed);
877 /* NOTE: this function supports braceful and braceless variable expansions,
878 * plus "extended" substitutions, unlike other exported parsing functions.
881 return parse_env_file_internal(f, fname, NEWLINE, merge_env_file_push, env, NULL);
884 static void write_env_var(FILE *f, const char *v) {
890 fputs_unlocked(v, f);
891 fputc_unlocked('\n', f);
896 fwrite_unlocked(v, 1, p-v, f);
898 if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
899 fputc_unlocked('\"', f);
902 if (strchr(SHELL_NEED_ESCAPE, *p))
903 fputc_unlocked('\\', f);
905 fputc_unlocked(*p, f);
908 fputc_unlocked('\"', f);
910 fputs_unlocked(p, f);
912 fputc_unlocked('\n', f);
915 int write_env_file(const char *fname, char **l) {
916 _cleanup_fclose_ FILE *f = NULL;
917 _cleanup_free_ char *p = NULL;
923 r = fopen_temporary(fname, &f, &p);
927 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
928 (void) fchmod_umask(fileno(f), 0644);
931 write_env_var(f, *i);
933 r = fflush_and_check(f);
935 if (rename(p, fname) >= 0)
945 int executable_is_script(const char *path, char **interpreter) {
946 _cleanup_free_ char *line = NULL;
953 r = read_one_line_file(path, &line);
954 if (r == -ENOBUFS) /* First line overly long? if so, then it's not a script */
959 if (!startswith(line, "#!"))
962 ans = strstrip(line + 2);
963 len = strcspn(ans, " \t");
968 ans = strndup(ans, len);
978 * Retrieve one field from a file like /proc/self/status. pattern
979 * should not include whitespace or the delimiter (':'). pattern matches only
980 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
981 * zeros after the ':' will be skipped. field must be freed afterwards.
982 * terminator specifies the terminating characters of the field value (not
983 * included in the value).
985 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
986 _cleanup_free_ char *status = NULL;
996 r = read_full_file(filename, &status, NULL);
1006 t = strstr(t, pattern);
1010 /* Check that pattern occurs in beginning of line. */
1011 pattern_ok = (t == status || t[-1] == '\n');
1013 t += strlen(pattern);
1015 } while (!pattern_ok);
1017 t += strspn(t, " \t");
1021 } while (*t != ':');
1026 t += strspn(t, " \t");
1028 /* Also skip zeros, because when this is used for
1029 * capabilities, we don't want the zeros. This way the
1030 * same capability set always maps to the same string,
1031 * irrespective of the total capability set size. For
1032 * other numbers it shouldn't matter. */
1033 t += strspn(t, "0");
1034 /* Back off one char if there's nothing but whitespace
1036 if (!*t || isspace(*t))
1040 len = strcspn(t, terminator);
1042 f = strndup(t, len);
1050 DIR *xopendirat(int fd, const char *name, int flags) {
1054 assert(!(flags & O_CREAT));
1056 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
1069 #if 0 /// UNNEEDED by elogind
1070 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
1077 if (!path_strv_resolve_uniq(search, root))
1080 STRV_FOREACH(i, search) {
1081 _cleanup_free_ char *p = NULL;
1085 p = strjoin(root, *i, "/", path);
1087 p = strjoin(*i, "/", path);
1097 if (errno != ENOENT)
1104 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
1105 _cleanup_strv_free_ char **copy = NULL;
1111 if (path_is_absolute(path)) {
1114 f = fopen(path, mode);
1123 copy = strv_copy((char**) search);
1127 return search_and_fopen_internal(path, mode, root, copy, _f);
1130 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
1131 _cleanup_strv_free_ char **s = NULL;
1133 if (path_is_absolute(path)) {
1136 f = fopen(path, mode);
1145 s = strv_split_nulstr(search);
1149 return search_and_fopen_internal(path, mode, root, s, _f);
1153 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1162 r = tempfn_xxxxxx(path, NULL, &t);
1166 fd = mkostemp_safe(t);
1172 f = fdopen(fd, "we");
1186 int fflush_and_check(FILE *f) {
1193 return errno > 0 ? -errno : -EIO;
1198 int fflush_sync_and_check(FILE *f) {
1203 r = fflush_and_check(f);
1207 if (fsync(fileno(f)) < 0)
1210 r = fsync_directory_of_file(fileno(f));
1217 /* This is much like mkostemp() but is subject to umask(). */
1218 int mkostemp_safe(char *pattern) {
1219 _cleanup_umask_ mode_t u = 0;
1226 fd = mkostemp(pattern, O_CLOEXEC);
1233 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1245 * /foo/bar/.#<extra>waldoXXXXXX
1249 if (!filename_is_valid(fn))
1252 extra = strempty(extra);
1254 t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1258 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1260 *ret = path_simplify(t, false);
1264 int tempfn_random(const char *p, const char *extra, char **ret) {
1278 * /foo/bar/.#<extra>waldobaa2a261115984a9
1282 if (!filename_is_valid(fn))
1285 extra = strempty(extra);
1287 t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1291 x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1294 for (i = 0; i < 16; i++) {
1295 *(x++) = hexchar(u & 0xF);
1301 *ret = path_simplify(t, false);
1305 #if 0 /// UNNEEDED by elogind
1306 int tempfn_random_child(const char *p, const char *extra, char **ret) {
1317 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1326 extra = strempty(extra);
1328 t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1332 x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
1335 for (i = 0; i < 16; i++) {
1336 *(x++) = hexchar(u & 0xF);
1342 *ret = path_simplify(t, false);
1346 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1347 char ln[DECIMAL_STR_MAX(n)+2];
1349 /* Creates a "timestamp" file, that contains nothing but a
1350 * usec_t timestamp, formatted in ASCII. */
1352 if (n <= 0 || n >= USEC_INFINITY)
1355 xsprintf(ln, USEC_FMT "\n", n);
1357 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1360 int read_timestamp_file(const char *fn, usec_t *ret) {
1361 _cleanup_free_ char *ln = NULL;
1365 r = read_one_line_file(fn, &ln);
1369 r = safe_atou64(ln, &t);
1373 if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1380 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1385 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1386 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1387 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1388 * element, but not before the first one. */
1398 r = fputs(separator, f);
1410 int open_tmpfile_unlinkable(const char *directory, int flags) {
1415 r = tmp_dir(&directory);
1420 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1422 /* Try O_TMPFILE first, if it is supported */
1423 fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1427 /* Fall back to unguessable name + unlinking */
1428 p = strjoina(directory, "/systemd-tmp-XXXXXX");
1430 fd = mkostemp_safe(p);
1439 #if 0 /// UNNEEDED by elogind
1440 int open_tmpfile_linkable(const char *target, int flags, char **ret_path) {
1441 _cleanup_free_ char *tmp = NULL;
1447 /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1448 assert((flags & O_EXCL) == 0);
1450 /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1451 * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1452 * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1455 _cleanup_free_ char *dn = NULL;
1457 dn = dirname_malloc(target);
1461 fd = open(dn, O_TMPFILE|flags, 0640);
1467 log_debug_errno(errno, "Failed to use O_TMPFILE on %s: %m", dn);
1470 r = tempfn_random(target, NULL, &tmp);
1474 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640);
1478 *ret_path = TAKE_PTR(tmp);
1484 int open_serialization_fd(const char *ident) {
1487 fd = memfd_create(ident, MFD_CLOEXEC);
1491 path = getpid_cached() == 1 ? "/run/systemd" : "/tmp";
1492 fd = open_tmpfile_unlinkable(path, O_RDWR|O_CLOEXEC);
1496 log_debug("Serializing %s to %s.", ident, path);
1498 log_debug("Serializing %s to memfd.", ident);
1503 #if 0 /// UNNEEDED by elogind
1504 int link_tmpfile(int fd, const char *path, const char *target) {
1509 /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1510 * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1511 * on the directory, and renameat2() is used instead.
1513 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1514 * operation currently (renameat2() does), and there is no nice way to emulate this. */
1517 if (rename_noreplace(AT_FDCWD, path, AT_FDCWD, target) < 0)
1520 char proc_fd_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
1522 xsprintf(proc_fd_path, "/proc/self/fd/%i", fd);
1524 if (linkat(AT_FDCWD, proc_fd_path, AT_FDCWD, target, AT_SYMLINK_FOLLOW) < 0)
1531 int read_nul_string(FILE *f, char **ret) {
1532 _cleanup_free_ char *x = NULL;
1533 size_t allocated = 0, n = 0;
1538 /* Reads a NUL-terminated string from the specified file. */
1543 if (!GREEDY_REALLOC(x, allocated, n+2))
1547 if (c == 0) /* Terminate at NUL byte */
1552 break; /* Terminate at EOF */
1571 int mkdtemp_malloc(const char *template, char **ret) {
1577 p = strdup(template);
1591 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile);
1593 int read_line(FILE *f, size_t limit, char **ret) {
1594 _cleanup_free_ char *buffer = NULL;
1595 size_t n = 0, allocated = 0, count = 0;
1599 /* Something like a bounded version of getline().
1601 * Considers EOF, \n and \0 end of line delimiters, and does not include these delimiters in the string
1604 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1605 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1607 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1608 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1610 * If a line shall be skipped ret may be initialized as NULL. */
1613 if (!GREEDY_REALLOC(buffer, allocated, 1))
1618 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
1628 c = fgetc_unlocked(f);
1630 /* if we read an error, and have no data to return, then propagate the error */
1631 if (ferror_unlocked(f) && n == 0)
1632 return errno > 0 ? -errno : -EIO;
1639 if (IN_SET(c, '\n', 0)) /* Reached a delimiter */
1643 if (!GREEDY_REALLOC(buffer, allocated, n + 2))
1646 buffer[n] = (char) c;
1656 *ret = TAKE_PTR(buffer);