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 write_string_filef(
211 WriteStringFileFlags flags,
212 const char *format, ...) {
214 _cleanup_free_ char *p = NULL;
218 va_start(ap, format);
219 r = vasprintf(&p, format, ap);
225 return write_string_file(fn, p, flags);
228 int read_one_line_file(const char *fn, char **line) {
229 _cleanup_fclose_ FILE *f = NULL;
239 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
241 r = read_line(f, LONG_LINE_MAX, line);
242 return r < 0 ? r : 0;
245 int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
246 _cleanup_fclose_ FILE *f = NULL;
247 _cleanup_free_ char *buf = NULL;
255 if (accept_extra_nl && endswith(blob, "\n"))
256 accept_extra_nl = false;
258 buf = malloc(l + accept_extra_nl + 1);
266 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
268 /* We try to read one byte more than we need, so that we know whether we hit eof */
270 k = fread(buf, 1, l + accept_extra_nl + 1, f);
272 return errno > 0 ? -errno : -EIO;
274 if (k != l && k != l + accept_extra_nl)
276 if (memcmp(buf, blob, l) != 0)
278 if (k > l && buf[l] != '\n')
284 int read_full_stream(FILE *f, char **contents, size_t *size) {
285 _cleanup_free_ char *buf = NULL;
296 if (fd >= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
297 * optimize our buffering) */
299 if (fstat(fileno(f), &st) < 0)
302 if (S_ISREG(st.st_mode)) {
305 if (st.st_size > READ_FULL_BYTES_MAX)
308 /* Start with the right file size, but be prepared for files from /proc which generally report a file
309 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
310 * already makes us notice the EOF. */
321 t = realloc(buf, n + 1);
327 k = fread(buf + l, 1, n - l, f);
332 return errno > 0 ? -errno : -EIO;
337 /* We aren't expecting fread() to return a short read outside
338 * of (error && eof), assert buffer is full and enlarge buffer.
343 if (n >= READ_FULL_BYTES_MAX)
346 n = MIN(n * 2, READ_FULL_BYTES_MAX);
350 *contents = TAKE_PTR(buf);
358 int read_full_file(const char *fn, char **contents, size_t *size) {
359 _cleanup_fclose_ FILE *f = NULL;
368 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
370 return read_full_stream(f, contents, size);
373 static int parse_env_file_internal(
377 int (*push) (const char *filename, unsigned line,
378 const char *key, char *value, void *userdata, int *n_pushed),
382 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;
383 _cleanup_free_ char *contents = NULL, *key = NULL, *value = NULL;
395 SINGLE_QUOTE_VALUE_ESCAPE,
397 DOUBLE_QUOTE_VALUE_ESCAPE,
405 r = read_full_stream(f, &contents, NULL);
407 r = read_full_file(fname, &contents, NULL);
411 for (p = contents; *p; p++) {
417 if (strchr(COMMENTS, c))
419 else if (!strchr(WHITESPACE, c)) {
421 last_key_whitespace = (size_t) -1;
423 if (!GREEDY_REALLOC(key, key_alloc, n_key+2))
431 if (strchr(newline, c)) {
435 } else if (c == '=') {
437 last_value_whitespace = (size_t) -1;
439 if (!strchr(WHITESPACE, c))
440 last_key_whitespace = (size_t) -1;
441 else if (last_key_whitespace == (size_t) -1)
442 last_key_whitespace = n_key;
444 if (!GREEDY_REALLOC(key, key_alloc, n_key+2))
453 if (strchr(newline, c)) {
461 /* strip trailing whitespace from key */
462 if (last_key_whitespace != (size_t) -1)
463 key[last_key_whitespace] = 0;
465 r = push(fname, line, key, value, userdata, n_pushed);
471 value_alloc = n_value = 0;
473 } else if (c == '\'')
474 state = SINGLE_QUOTE_VALUE;
476 state = DOUBLE_QUOTE_VALUE;
478 state = VALUE_ESCAPE;
479 else if (!strchr(WHITESPACE, c)) {
482 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
485 value[n_value++] = c;
491 if (strchr(newline, c)) {
500 /* Chomp off trailing whitespace from value */
501 if (last_value_whitespace != (size_t) -1)
502 value[last_value_whitespace] = 0;
504 /* strip trailing whitespace from key */
505 if (last_key_whitespace != (size_t) -1)
506 key[last_key_whitespace] = 0;
508 r = push(fname, line, key, value, userdata, n_pushed);
514 value_alloc = n_value = 0;
516 } else if (c == '\\') {
517 state = VALUE_ESCAPE;
518 last_value_whitespace = (size_t) -1;
520 if (!strchr(WHITESPACE, c))
521 last_value_whitespace = (size_t) -1;
522 else if (last_value_whitespace == (size_t) -1)
523 last_value_whitespace = n_value;
525 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
528 value[n_value++] = c;
536 if (!strchr(newline, c)) {
537 /* Escaped newlines we eat up entirely */
538 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
541 value[n_value++] = c;
545 case SINGLE_QUOTE_VALUE:
549 state = SINGLE_QUOTE_VALUE_ESCAPE;
551 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
554 value[n_value++] = c;
559 case SINGLE_QUOTE_VALUE_ESCAPE:
560 state = SINGLE_QUOTE_VALUE;
562 if (!strchr(newline, c)) {
563 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
566 value[n_value++] = c;
570 case DOUBLE_QUOTE_VALUE:
574 state = DOUBLE_QUOTE_VALUE_ESCAPE;
576 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
579 value[n_value++] = c;
584 case DOUBLE_QUOTE_VALUE_ESCAPE:
585 state = DOUBLE_QUOTE_VALUE;
587 if (!strchr(newline, c)) {
588 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
591 value[n_value++] = c;
597 state = COMMENT_ESCAPE;
598 else if (strchr(newline, c)) {
615 SINGLE_QUOTE_VALUE_ESCAPE,
617 DOUBLE_QUOTE_VALUE_ESCAPE)) {
625 if (last_value_whitespace != (size_t) -1)
626 value[last_value_whitespace] = 0;
628 /* strip trailing whitespace from key */
629 if (last_key_whitespace != (size_t) -1)
630 key[last_key_whitespace] = 0;
632 r = push(fname, line, key, value, userdata, n_pushed);
642 static int check_utf8ness_and_warn(
643 const char *filename, unsigned line,
644 const char *key, char *value) {
646 if (!utf8_is_valid(key)) {
647 _cleanup_free_ char *p = NULL;
649 p = utf8_escape_invalid(key);
650 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p);
654 if (value && !utf8_is_valid(value)) {
655 _cleanup_free_ char *p = NULL;
657 p = utf8_escape_invalid(value);
658 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, p);
665 static int parse_env_file_push(
666 const char *filename, unsigned line,
667 const char *key, char *value,
672 va_list aq, *ap = userdata;
675 r = check_utf8ness_and_warn(filename, line, key, value);
681 while ((k = va_arg(aq, const char *))) {
684 v = va_arg(aq, char **);
717 r = parse_env_file_internal(f, fname, newline, parse_env_file_push, &aq, &n_pushed);
734 va_start(ap, newline);
735 r = parse_env_filev(f, fname, newline, ap);
741 #if 0 /// UNNEEDED by elogind
742 static int load_env_file_push(
743 const char *filename, unsigned line,
744 const char *key, char *value,
747 char ***m = userdata;
751 r = check_utf8ness_and_warn(filename, line, key, value);
755 p = strjoin(key, "=", value);
759 r = strv_env_replace(m, p);
772 int load_env_file(FILE *f, const char *fname, const char *newline, char ***rl) {
779 r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
790 static int load_env_file_push_pairs(
791 const char *filename, unsigned line,
792 const char *key, char *value,
795 char ***m = userdata;
798 r = check_utf8ness_and_warn(filename, line, key, value);
802 r = strv_extend(m, key);
807 r = strv_extend(m, "");
811 r = strv_push(m, value);
822 int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
829 r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
838 #if 0 /// UNNEEDED by elogind
840 static int merge_env_file_push(
841 const char *filename, unsigned line,
842 const char *key, char *value,
846 char ***env = userdata;
847 char *expanded_value;
852 log_error("%s:%u: invalid syntax (around \"%s\"), ignoring.", strna(filename), line, key);
856 if (!env_name_is_valid(key)) {
857 log_error("%s:%u: invalid variable name \"%s\", ignoring.", strna(filename), line, key);
862 expanded_value = replace_env(value, *env,
863 REPLACE_ENV_USE_ENVIRONMENT|
864 REPLACE_ENV_ALLOW_BRACELESS|
865 REPLACE_ENV_ALLOW_EXTENDED);
869 free_and_replace(value, expanded_value);
871 return load_env_file_push(filename, line, key, value, env, n_pushed);
879 /* NOTE: this function supports braceful and braceless variable expansions,
880 * plus "extended" substitutions, unlike other exported parsing functions.
883 return parse_env_file_internal(f, fname, NEWLINE, merge_env_file_push, env, NULL);
886 static void write_env_var(FILE *f, const char *v) {
892 fputs_unlocked(v, f);
893 fputc_unlocked('\n', f);
898 fwrite_unlocked(v, 1, p-v, f);
900 if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
901 fputc_unlocked('\"', f);
904 if (strchr(SHELL_NEED_ESCAPE, *p))
905 fputc_unlocked('\\', f);
907 fputc_unlocked(*p, f);
910 fputc_unlocked('\"', f);
912 fputs_unlocked(p, f);
914 fputc_unlocked('\n', f);
917 int write_env_file(const char *fname, char **l) {
918 _cleanup_fclose_ FILE *f = NULL;
919 _cleanup_free_ char *p = NULL;
925 r = fopen_temporary(fname, &f, &p);
929 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
930 (void) fchmod_umask(fileno(f), 0644);
933 write_env_var(f, *i);
935 r = fflush_and_check(f);
937 if (rename(p, fname) >= 0)
947 int executable_is_script(const char *path, char **interpreter) {
948 _cleanup_free_ char *line = NULL;
955 r = read_one_line_file(path, &line);
956 if (r == -ENOBUFS) /* First line overly long? if so, then it's not a script */
961 if (!startswith(line, "#!"))
964 ans = strstrip(line + 2);
965 len = strcspn(ans, " \t");
970 ans = strndup(ans, len);
980 * Retrieve one field from a file like /proc/self/status. pattern
981 * should not include whitespace or the delimiter (':'). pattern matches only
982 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
983 * zeros after the ':' will be skipped. field must be freed afterwards.
984 * terminator specifies the terminating characters of the field value (not
985 * included in the value).
987 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
988 _cleanup_free_ char *status = NULL;
998 r = read_full_file(filename, &status, NULL);
1008 t = strstr(t, pattern);
1012 /* Check that pattern occurs in beginning of line. */
1013 pattern_ok = (t == status || t[-1] == '\n');
1015 t += strlen(pattern);
1017 } while (!pattern_ok);
1019 t += strspn(t, " \t");
1023 } while (*t != ':');
1028 t += strspn(t, " \t");
1030 /* Also skip zeros, because when this is used for
1031 * capabilities, we don't want the zeros. This way the
1032 * same capability set always maps to the same string,
1033 * irrespective of the total capability set size. For
1034 * other numbers it shouldn't matter. */
1035 t += strspn(t, "0");
1036 /* Back off one char if there's nothing but whitespace
1038 if (!*t || isspace(*t))
1042 len = strcspn(t, terminator);
1044 f = strndup(t, len);
1052 DIR *xopendirat(int fd, const char *name, int flags) {
1056 assert(!(flags & O_CREAT));
1058 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
1071 #if 0 /// UNNEEDED by elogind
1072 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
1079 if (!path_strv_resolve_uniq(search, root))
1082 STRV_FOREACH(i, search) {
1083 _cleanup_free_ char *p = NULL;
1087 p = strjoin(root, *i, "/", path);
1089 p = strjoin(*i, "/", path);
1099 if (errno != ENOENT)
1106 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
1107 _cleanup_strv_free_ char **copy = NULL;
1113 if (path_is_absolute(path)) {
1116 f = fopen(path, mode);
1125 copy = strv_copy((char**) search);
1129 return search_and_fopen_internal(path, mode, root, copy, _f);
1132 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
1133 _cleanup_strv_free_ char **s = NULL;
1135 if (path_is_absolute(path)) {
1138 f = fopen(path, mode);
1147 s = strv_split_nulstr(search);
1151 return search_and_fopen_internal(path, mode, root, s, _f);
1155 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1164 r = tempfn_xxxxxx(path, NULL, &t);
1168 fd = mkostemp_safe(t);
1174 f = fdopen(fd, "we");
1188 int fflush_and_check(FILE *f) {
1195 return errno > 0 ? -errno : -EIO;
1200 int fflush_sync_and_check(FILE *f) {
1205 r = fflush_and_check(f);
1209 if (fsync(fileno(f)) < 0)
1212 r = fsync_directory_of_file(fileno(f));
1219 /* This is much like mkostemp() but is subject to umask(). */
1220 int mkostemp_safe(char *pattern) {
1221 _cleanup_umask_ mode_t u = 0;
1228 fd = mkostemp(pattern, O_CLOEXEC);
1235 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1247 * /foo/bar/.#<extra>waldoXXXXXX
1251 if (!filename_is_valid(fn))
1254 extra = strempty(extra);
1256 t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1260 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1262 *ret = path_simplify(t, false);
1266 int tempfn_random(const char *p, const char *extra, char **ret) {
1280 * /foo/bar/.#<extra>waldobaa2a261115984a9
1284 if (!filename_is_valid(fn))
1287 extra = strempty(extra);
1289 t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1293 x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1296 for (i = 0; i < 16; i++) {
1297 *(x++) = hexchar(u & 0xF);
1303 *ret = path_simplify(t, false);
1307 #if 0 /// UNNEEDED by elogind
1308 int tempfn_random_child(const char *p, const char *extra, char **ret) {
1319 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1328 extra = strempty(extra);
1330 t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1334 x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
1337 for (i = 0; i < 16; i++) {
1338 *(x++) = hexchar(u & 0xF);
1344 *ret = path_simplify(t, false);
1348 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1349 char ln[DECIMAL_STR_MAX(n)+2];
1351 /* Creates a "timestamp" file, that contains nothing but a
1352 * usec_t timestamp, formatted in ASCII. */
1354 if (n <= 0 || n >= USEC_INFINITY)
1357 xsprintf(ln, USEC_FMT "\n", n);
1359 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1362 int read_timestamp_file(const char *fn, usec_t *ret) {
1363 _cleanup_free_ char *ln = NULL;
1367 r = read_one_line_file(fn, &ln);
1371 r = safe_atou64(ln, &t);
1375 if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1382 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1387 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1388 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1389 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1390 * element, but not before the first one. */
1400 r = fputs(separator, f);
1412 int open_tmpfile_unlinkable(const char *directory, int flags) {
1417 r = tmp_dir(&directory);
1422 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1424 /* Try O_TMPFILE first, if it is supported */
1425 fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1429 /* Fall back to unguessable name + unlinking */
1430 p = strjoina(directory, "/systemd-tmp-XXXXXX");
1432 fd = mkostemp_safe(p);
1441 #if 0 /// UNNEEDED by elogind
1442 int open_tmpfile_linkable(const char *target, int flags, char **ret_path) {
1443 _cleanup_free_ char *tmp = NULL;
1449 /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1450 assert((flags & O_EXCL) == 0);
1452 /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1453 * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1454 * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1457 _cleanup_free_ char *dn = NULL;
1459 dn = dirname_malloc(target);
1463 fd = open(dn, O_TMPFILE|flags, 0640);
1469 log_debug_errno(errno, "Failed to use O_TMPFILE on %s: %m", dn);
1472 r = tempfn_random(target, NULL, &tmp);
1476 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640);
1480 *ret_path = TAKE_PTR(tmp);
1486 int open_serialization_fd(const char *ident) {
1489 fd = memfd_create(ident, MFD_CLOEXEC);
1493 path = getpid_cached() == 1 ? "/run/systemd" : "/tmp";
1494 fd = open_tmpfile_unlinkable(path, O_RDWR|O_CLOEXEC);
1498 log_debug("Serializing %s to %s.", ident, path);
1500 log_debug("Serializing %s to memfd.", ident);
1505 #if 0 /// UNNEEDED by elogind
1506 int link_tmpfile(int fd, const char *path, const char *target) {
1511 /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1512 * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1513 * on the directory, and renameat2() is used instead.
1515 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1516 * operation currently (renameat2() does), and there is no nice way to emulate this. */
1519 if (rename_noreplace(AT_FDCWD, path, AT_FDCWD, target) < 0)
1522 char proc_fd_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
1524 xsprintf(proc_fd_path, "/proc/self/fd/%i", fd);
1526 if (linkat(AT_FDCWD, proc_fd_path, AT_FDCWD, target, AT_SYMLINK_FOLLOW) < 0)
1533 int read_nul_string(FILE *f, char **ret) {
1534 _cleanup_free_ char *x = NULL;
1535 size_t allocated = 0, n = 0;
1540 /* Reads a NUL-terminated string from the specified file. */
1545 if (!GREEDY_REALLOC(x, allocated, n+2))
1549 if (c == 0) /* Terminate at NUL byte */
1554 break; /* Terminate at EOF */
1573 int mkdtemp_malloc(const char *template, char **ret) {
1574 _cleanup_free_ char *p = NULL;
1580 p = strdup(template);
1588 p = strjoin(tmp, "/XXXXXX");
1601 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile);
1603 int read_line(FILE *f, size_t limit, char **ret) {
1604 _cleanup_free_ char *buffer = NULL;
1605 size_t n = 0, allocated = 0, count = 0;
1609 /* Something like a bounded version of getline().
1611 * Considers EOF, \n and \0 end of line delimiters, and does not include these delimiters in the string
1614 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1615 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1617 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1618 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1620 * If a line shall be skipped ret may be initialized as NULL. */
1623 if (!GREEDY_REALLOC(buffer, allocated, 1))
1628 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
1638 c = fgetc_unlocked(f);
1640 /* if we read an error, and have no data to return, then propagate the error */
1641 if (ferror_unlocked(f) && n == 0)
1642 return errno > 0 ? -errno : -EIO;
1649 if (IN_SET(c, '\n', 0)) /* Reached a delimiter */
1653 if (!GREEDY_REALLOC(buffer, allocated, n + 2))
1656 buffer[n] = (char) c;
1666 *ret = TAKE_PTR(buffer);