1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 #include <sys/types.h>
16 #include "alloc-util.h"
23 #include "hexdecoct.h"
27 #include "parse-util.h"
28 #include "path-util.h"
29 #include "process-util.h"
30 #include "random-util.h"
31 #include "stdio-util.h"
32 #include "string-util.h"
34 #include "time-util.h"
35 #include "umask-util.h"
38 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
40 int write_string_stream_ts(
43 WriteStringFileFlags flags
,
44 struct timespec
*ts
) {
55 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
57 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
58 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
59 * that the write goes out in one go, instead of two */
61 line
= strjoina(line
, "\n");
65 if (fputs(line
, f
) == EOF
)
69 if (fputc('\n', f
) == EOF
)
72 if (flags
& WRITE_STRING_FILE_SYNC
)
73 r
= fflush_sync_and_check(f
);
75 r
= fflush_and_check(f
);
80 struct timespec twice
[2] = {*ts
, *ts
};
82 if (futimens(fileno(f
), twice
) < 0)
89 static int write_string_file_atomic(
92 WriteStringFileFlags flags
,
93 struct timespec
*ts
) {
95 _cleanup_fclose_
FILE *f
= NULL
;
96 _cleanup_free_
char *p
= NULL
;
102 r
= fopen_temporary(fn
, &f
, &p
);
106 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
107 (void) fchmod_umask(fileno(f
), 0644);
109 r
= write_string_stream_ts(f
, line
, flags
, ts
);
113 if (rename(p
, fn
) < 0) {
125 int write_string_file_ts(
128 WriteStringFileFlags flags
,
129 struct timespec
*ts
) {
131 _cleanup_fclose_
FILE *f
= NULL
;
137 /* We don't know how to verify whether the file contents was already on-disk. */
138 assert(!((flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
) && (flags
& WRITE_STRING_FILE_SYNC
)));
140 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
141 assert(flags
& WRITE_STRING_FILE_CREATE
);
143 r
= write_string_file_atomic(fn
, line
, flags
, ts
);
151 if (flags
& WRITE_STRING_FILE_CREATE
) {
160 /* We manually build our own version of fopen(..., "we") that
161 * works without O_CREAT */
162 fd
= open(fn
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
| ((flags
& WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0));
168 f
= fdopen(fd
, "we");
176 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
178 if (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)
179 setvbuf(f
, NULL
, _IONBF
, 0);
181 r
= write_string_stream_ts(f
, line
, flags
, ts
);
188 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
193 /* OK, the operation failed, but let's see if the right
194 * contents in place already. If so, eat up the error. */
196 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
203 int write_string_filef(
205 WriteStringFileFlags flags
,
206 const char *format
, ...) {
208 _cleanup_free_
char *p
= NULL
;
212 va_start(ap
, format
);
213 r
= vasprintf(&p
, format
, ap
);
219 return write_string_file(fn
, p
, flags
);
222 int read_one_line_file(const char *fn
, char **line
) {
223 _cleanup_fclose_
FILE *f
= NULL
;
233 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
235 r
= read_line(f
, LONG_LINE_MAX
, line
);
236 return r
< 0 ? r
: 0;
239 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
240 _cleanup_fclose_
FILE *f
= NULL
;
241 _cleanup_free_
char *buf
= NULL
;
249 if (accept_extra_nl
&& endswith(blob
, "\n"))
250 accept_extra_nl
= false;
252 buf
= malloc(l
+ accept_extra_nl
+ 1);
260 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
262 /* We try to read one byte more than we need, so that we know whether we hit eof */
264 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
266 return errno
> 0 ? -errno
: -EIO
;
268 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
270 if (memcmp(buf
, blob
, l
) != 0)
272 if (k
> l
&& buf
[l
] != '\n')
278 int read_full_stream(FILE *f
, char **contents
, size_t *size
) {
279 _cleanup_free_
char *buf
= NULL
;
290 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
291 * optimize our buffering) */
293 if (fstat(fileno(f
), &st
) < 0)
296 if (S_ISREG(st
.st_mode
)) {
299 if (st
.st_size
> READ_FULL_BYTES_MAX
)
302 /* Start with the right file size, but be prepared for files from /proc which generally report a file
303 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
304 * already makes us notice the EOF. */
315 t
= realloc(buf
, n
+ 1);
321 k
= fread(buf
+ l
, 1, n
- l
, f
);
326 return errno
> 0 ? -errno
: -EIO
;
331 /* We aren't expecting fread() to return a short read outside
332 * of (error && eof), assert buffer is full and enlarge buffer.
337 if (n
>= READ_FULL_BYTES_MAX
)
340 n
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
344 *contents
= TAKE_PTR(buf
);
352 int read_full_file(const char *fn
, char **contents
, size_t *size
) {
353 _cleanup_fclose_
FILE *f
= NULL
;
362 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
364 return read_full_stream(f
, contents
, size
);
367 static int parse_env_file_internal(
370 int (*push
) (const char *filename
, unsigned line
,
371 const char *key
, char *value
, void *userdata
, int *n_pushed
),
375 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;
376 _cleanup_free_
char *contents
= NULL
, *key
= NULL
, *value
= NULL
;
388 SINGLE_QUOTE_VALUE_ESCAPE
,
390 DOUBLE_QUOTE_VALUE_ESCAPE
,
396 r
= read_full_stream(f
, &contents
, NULL
);
398 r
= read_full_file(fname
, &contents
, NULL
);
402 for (p
= contents
; *p
; p
++) {
408 if (strchr(COMMENTS
, c
))
410 else if (!strchr(WHITESPACE
, c
)) {
412 last_key_whitespace
= (size_t) -1;
414 if (!GREEDY_REALLOC(key
, key_alloc
, n_key
+2))
422 if (strchr(NEWLINE
, c
)) {
426 } else if (c
== '=') {
428 last_value_whitespace
= (size_t) -1;
430 if (!strchr(WHITESPACE
, c
))
431 last_key_whitespace
= (size_t) -1;
432 else if (last_key_whitespace
== (size_t) -1)
433 last_key_whitespace
= n_key
;
435 if (!GREEDY_REALLOC(key
, key_alloc
, n_key
+2))
444 if (strchr(NEWLINE
, c
)) {
452 /* strip trailing whitespace from key */
453 if (last_key_whitespace
!= (size_t) -1)
454 key
[last_key_whitespace
] = 0;
456 r
= push(fname
, line
, key
, value
, userdata
, n_pushed
);
462 value_alloc
= n_value
= 0;
464 } else if (c
== '\'')
465 state
= SINGLE_QUOTE_VALUE
;
467 state
= DOUBLE_QUOTE_VALUE
;
469 state
= VALUE_ESCAPE
;
470 else if (!strchr(WHITESPACE
, c
)) {
473 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
476 value
[n_value
++] = c
;
482 if (strchr(NEWLINE
, c
)) {
491 /* Chomp off trailing whitespace from value */
492 if (last_value_whitespace
!= (size_t) -1)
493 value
[last_value_whitespace
] = 0;
495 /* strip trailing whitespace from key */
496 if (last_key_whitespace
!= (size_t) -1)
497 key
[last_key_whitespace
] = 0;
499 r
= push(fname
, line
, key
, value
, userdata
, n_pushed
);
505 value_alloc
= n_value
= 0;
507 } else if (c
== '\\') {
508 state
= VALUE_ESCAPE
;
509 last_value_whitespace
= (size_t) -1;
511 if (!strchr(WHITESPACE
, c
))
512 last_value_whitespace
= (size_t) -1;
513 else if (last_value_whitespace
== (size_t) -1)
514 last_value_whitespace
= n_value
;
516 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
519 value
[n_value
++] = c
;
527 if (!strchr(NEWLINE
, c
)) {
528 /* Escaped newlines we eat up entirely */
529 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
532 value
[n_value
++] = c
;
536 case SINGLE_QUOTE_VALUE
:
540 state
= SINGLE_QUOTE_VALUE_ESCAPE
;
542 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
545 value
[n_value
++] = c
;
550 case SINGLE_QUOTE_VALUE_ESCAPE
:
551 state
= SINGLE_QUOTE_VALUE
;
553 if (!strchr(NEWLINE
, c
)) {
554 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
557 value
[n_value
++] = c
;
561 case DOUBLE_QUOTE_VALUE
:
565 state
= DOUBLE_QUOTE_VALUE_ESCAPE
;
567 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
570 value
[n_value
++] = c
;
575 case DOUBLE_QUOTE_VALUE_ESCAPE
:
576 state
= DOUBLE_QUOTE_VALUE
;
578 if (!strchr(NEWLINE
, c
)) {
579 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
582 value
[n_value
++] = c
;
588 state
= COMMENT_ESCAPE
;
589 else if (strchr(NEWLINE
, c
)) {
606 SINGLE_QUOTE_VALUE_ESCAPE
,
608 DOUBLE_QUOTE_VALUE_ESCAPE
)) {
616 if (last_value_whitespace
!= (size_t) -1)
617 value
[last_value_whitespace
] = 0;
619 /* strip trailing whitespace from key */
620 if (last_key_whitespace
!= (size_t) -1)
621 key
[last_key_whitespace
] = 0;
623 r
= push(fname
, line
, key
, value
, userdata
, n_pushed
);
633 static int check_utf8ness_and_warn(
634 const char *filename
, unsigned line
,
635 const char *key
, char *value
) {
637 if (!utf8_is_valid(key
)) {
638 _cleanup_free_
char *p
= NULL
;
640 p
= utf8_escape_invalid(key
);
641 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename
), line
, p
);
645 if (value
&& !utf8_is_valid(value
)) {
646 _cleanup_free_
char *p
= NULL
;
648 p
= utf8_escape_invalid(value
);
649 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename
), line
, key
, p
);
656 static int parse_env_file_push(
657 const char *filename
, unsigned line
,
658 const char *key
, char *value
,
663 va_list aq
, *ap
= userdata
;
666 r
= check_utf8ness_and_warn(filename
, line
, key
, value
);
672 while ((k
= va_arg(aq
, const char *))) {
675 v
= va_arg(aq
, char **);
704 r
= parse_env_file_internal(f
, fname
, parse_env_file_push
, &aq
, &n_pushed
);
712 int parse_env_file_sentinel(
721 r
= parse_env_filev(f
, fname
, ap
);
727 static int load_env_file_push(
728 const char *filename
, unsigned line
,
729 const char *key
, char *value
,
732 char ***m
= userdata
;
736 r
= check_utf8ness_and_warn(filename
, line
, key
, value
);
740 p
= strjoin(key
, "=", value
);
744 r
= strv_env_replace(m
, p
);
757 int load_env_file(FILE *f
, const char *fname
, char ***rl
) {
761 r
= parse_env_file_internal(f
, fname
, 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
, char ***rl
) {
807 r
= parse_env_file_internal(f
, fname
, load_env_file_push_pairs
, &m
, NULL
);
817 static int merge_env_file_push(
818 const char *filename
, unsigned line
,
819 const char *key
, char *value
,
823 char ***env
= userdata
;
824 char *expanded_value
;
829 log_error("%s:%u: invalid syntax (around \"%s\"), ignoring.", strna(filename
), line
, key
);
833 if (!env_name_is_valid(key
)) {
834 log_error("%s:%u: invalid variable name \"%s\", ignoring.", strna(filename
), line
, key
);
839 expanded_value
= replace_env(value
, *env
,
840 REPLACE_ENV_USE_ENVIRONMENT
|
841 REPLACE_ENV_ALLOW_BRACELESS
|
842 REPLACE_ENV_ALLOW_EXTENDED
);
846 free_and_replace(value
, expanded_value
);
848 return load_env_file_push(filename
, line
, key
, value
, env
, n_pushed
);
856 /* NOTE: this function supports braceful and braceless variable expansions,
857 * plus "extended" substitutions, unlike other exported parsing functions.
860 return parse_env_file_internal(f
, fname
, merge_env_file_push
, env
, NULL
);
863 static void write_env_var(FILE *f
, const char *v
) {
869 fputs_unlocked(v
, f
);
870 fputc_unlocked('\n', f
);
875 fwrite_unlocked(v
, 1, p
-v
, f
);
877 if (string_has_cc(p
, NULL
) || chars_intersect(p
, WHITESPACE SHELL_NEED_QUOTES
)) {
878 fputc_unlocked('\"', f
);
881 if (strchr(SHELL_NEED_ESCAPE
, *p
))
882 fputc_unlocked('\\', f
);
884 fputc_unlocked(*p
, f
);
887 fputc_unlocked('\"', f
);
889 fputs_unlocked(p
, f
);
891 fputc_unlocked('\n', f
);
894 int write_env_file(const char *fname
, char **l
) {
895 _cleanup_fclose_
FILE *f
= NULL
;
896 _cleanup_free_
char *p
= NULL
;
902 r
= fopen_temporary(fname
, &f
, &p
);
906 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
907 (void) fchmod_umask(fileno(f
), 0644);
910 write_env_var(f
, *i
);
912 r
= fflush_and_check(f
);
914 if (rename(p
, fname
) >= 0)
924 int executable_is_script(const char *path
, char **interpreter
) {
925 _cleanup_free_
char *line
= NULL
;
932 r
= read_one_line_file(path
, &line
);
933 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
938 if (!startswith(line
, "#!"))
941 ans
= strstrip(line
+ 2);
942 len
= strcspn(ans
, " \t");
947 ans
= strndup(ans
, len
);
956 * Retrieve one field from a file like /proc/self/status. pattern
957 * should not include whitespace or the delimiter (':'). pattern matches only
958 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
959 * zeros after the ':' will be skipped. field must be freed afterwards.
960 * terminator specifies the terminating characters of the field value (not
961 * included in the value).
963 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
964 _cleanup_free_
char *status
= NULL
;
974 r
= read_full_file(filename
, &status
, NULL
);
984 t
= strstr(t
, pattern
);
988 /* Check that pattern occurs in beginning of line. */
989 pattern_ok
= (t
== status
|| t
[-1] == '\n');
991 t
+= strlen(pattern
);
993 } while (!pattern_ok
);
995 t
+= strspn(t
, " \t");
1004 t
+= strspn(t
, " \t");
1006 /* Also skip zeros, because when this is used for
1007 * capabilities, we don't want the zeros. This way the
1008 * same capability set always maps to the same string,
1009 * irrespective of the total capability set size. For
1010 * other numbers it shouldn't matter. */
1011 t
+= strspn(t
, "0");
1012 /* Back off one char if there's nothing but whitespace
1014 if (!*t
|| isspace(*t
))
1018 len
= strcspn(t
, terminator
);
1020 f
= strndup(t
, len
);
1028 DIR *xopendirat(int fd
, const char *name
, int flags
) {
1032 assert(!(flags
& O_CREAT
));
1034 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
1047 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
1054 if (!path_strv_resolve_uniq(search
, root
))
1057 STRV_FOREACH(i
, search
) {
1058 _cleanup_free_
char *p
= NULL
;
1062 p
= strjoin(root
, *i
, "/", path
);
1064 p
= strjoin(*i
, "/", path
);
1074 if (errno
!= ENOENT
)
1081 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
1082 _cleanup_strv_free_
char **copy
= NULL
;
1088 if (path_is_absolute(path
)) {
1091 f
= fopen(path
, mode
);
1100 copy
= strv_copy((char**) search
);
1104 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
1107 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
1108 _cleanup_strv_free_
char **s
= NULL
;
1110 if (path_is_absolute(path
)) {
1113 f
= fopen(path
, mode
);
1122 s
= strv_split_nulstr(search
);
1126 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
1129 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
1138 r
= tempfn_xxxxxx(path
, NULL
, &t
);
1142 fd
= mkostemp_safe(t
);
1148 f
= fdopen(fd
, "we");
1162 int fflush_and_check(FILE *f
) {
1169 return errno
> 0 ? -errno
: -EIO
;
1174 int fflush_sync_and_check(FILE *f
) {
1179 r
= fflush_and_check(f
);
1183 if (fsync(fileno(f
)) < 0)
1186 r
= fsync_directory_of_file(fileno(f
));
1193 /* This is much like mkostemp() but is subject to umask(). */
1194 int mkostemp_safe(char *pattern
) {
1195 _cleanup_umask_ mode_t u
= 0;
1202 fd
= mkostemp(pattern
, O_CLOEXEC
);
1209 int fmkostemp_safe(char *pattern
, const char *mode
, FILE **ret_f
) {
1213 fd
= mkostemp_safe(pattern
);
1217 f
= fdopen(fd
, mode
);
1227 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
1235 if (path_equal(p
, "/"))
1243 * /foo/bar/.#<extra>waldoXXXXXX
1247 if (!filename_is_valid(fn
))
1250 extra
= strempty(extra
);
1252 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
1256 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
1258 *ret
= path_simplify(t
, false);
1262 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
1272 if (path_equal(p
, "/"))
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 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
1318 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1327 extra
= strempty(extra
);
1329 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
1334 x
= stpcpy(stpcpy(t
, ".#"), extra
);
1336 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
1339 for (i
= 0; i
< 16; i
++) {
1340 *(x
++) = hexchar(u
& 0xF);
1346 *ret
= path_simplify(t
, false);
1350 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
1351 char ln
[DECIMAL_STR_MAX(n
)+2];
1353 /* Creates a "timestamp" file, that contains nothing but a
1354 * usec_t timestamp, formatted in ASCII. */
1356 if (n
<= 0 || n
>= USEC_INFINITY
)
1359 xsprintf(ln
, USEC_FMT
"\n", n
);
1361 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
1364 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
1365 _cleanup_free_
char *ln
= NULL
;
1369 r
= read_one_line_file(fn
, &ln
);
1373 r
= safe_atou64(ln
, &t
);
1377 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
1384 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
1389 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1390 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1391 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1392 * element, but not before the first one. */
1402 r
= fputs(separator
, f
);
1413 int open_tmpfile_unlinkable(const char *directory
, int flags
) {
1418 r
= tmp_dir(&directory
);
1421 } else if (isempty(directory
))
1424 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1426 /* Try O_TMPFILE first, if it is supported */
1427 fd
= open(directory
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
1431 /* Fall back to unguessable name + unlinking */
1432 p
= strjoina(directory
, "/systemd-tmp-XXXXXX");
1434 fd
= mkostemp_safe(p
);
1443 int open_tmpfile_linkable(const char *target
, int flags
, char **ret_path
) {
1444 _cleanup_free_
char *tmp
= NULL
;
1450 /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1451 assert((flags
& O_EXCL
) == 0);
1453 /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1454 * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1455 * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1457 fd
= open_parent(target
, O_TMPFILE
|flags
, 0640);
1463 log_debug_errno(fd
, "Failed to use O_TMPFILE for %s: %m", target
);
1465 r
= tempfn_random(target
, NULL
, &tmp
);
1469 fd
= open(tmp
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NOCTTY
|flags
, 0640);
1473 *ret_path
= TAKE_PTR(tmp
);
1478 int open_serialization_fd(const char *ident
) {
1481 fd
= memfd_create(ident
, MFD_CLOEXEC
);
1485 path
= getpid_cached() == 1 ? "/run/systemd" : "/tmp";
1486 fd
= open_tmpfile_unlinkable(path
, O_RDWR
|O_CLOEXEC
);
1490 log_debug("Serializing %s to %s.", ident
, path
);
1492 log_debug("Serializing %s to memfd.", ident
);
1497 int link_tmpfile(int fd
, const char *path
, const char *target
) {
1503 /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1504 * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1505 * on the directory, and renameat2() is used instead.
1507 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1508 * operation currently (renameat2() does), and there is no nice way to emulate this. */
1511 r
= rename_noreplace(AT_FDCWD
, path
, AT_FDCWD
, target
);
1515 char proc_fd_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(fd
) + 1];
1517 xsprintf(proc_fd_path
, "/proc/self/fd/%i", fd
);
1519 if (linkat(AT_FDCWD
, proc_fd_path
, AT_FDCWD
, target
, AT_SYMLINK_FOLLOW
) < 0)
1526 int read_nul_string(FILE *f
, char **ret
) {
1527 _cleanup_free_
char *x
= NULL
;
1528 size_t allocated
= 0, n
= 0;
1533 /* Reads a NUL-terminated string from the specified file. */
1538 if (!GREEDY_REALLOC(x
, allocated
, n
+2))
1542 if (c
== 0) /* Terminate at NUL byte */
1547 break; /* Terminate at EOF */
1566 int mkdtemp_malloc(const char *template, char **ret
) {
1567 _cleanup_free_
char *p
= NULL
;
1573 p
= strdup(template);
1581 p
= strjoin(tmp
, "/XXXXXX");
1593 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile
);
1595 int read_line(FILE *f
, size_t limit
, char **ret
) {
1596 _cleanup_free_
char *buffer
= NULL
;
1597 size_t n
= 0, allocated
= 0, count
= 0;
1601 /* Something like a bounded version of getline().
1603 * Considers EOF, \n and \0 end of line delimiters, and does not include these delimiters in the string
1606 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1607 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1609 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1610 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1612 * If a line shall be skipped ret may be initialized as NULL. */
1615 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
1620 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
1630 c
= fgetc_unlocked(f
);
1632 /* if we read an error, and have no data to return, then propagate the error */
1633 if (ferror_unlocked(f
) && n
== 0)
1634 return errno
> 0 ? -errno
: -EIO
;
1641 if (IN_SET(c
, '\n', 0)) /* Reached a delimiter */
1645 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
1648 buffer
[n
] = (char) c
;
1658 *ret
= TAKE_PTR(buffer
);