1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 #include <sys/types.h>
16 #include "alloc-util.h"
24 #include "hexdecoct.h"
28 #include "parse-util.h"
29 #include "path-util.h"
30 #include "process-util.h"
31 #include "random-util.h"
32 #include "stdio-util.h"
33 #include "string-util.h"
35 #include "time-util.h"
36 #include "umask-util.h"
39 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
41 int write_string_stream_ts(
44 WriteStringFileFlags flags
,
45 struct timespec
*ts
) {
56 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
58 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
59 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
60 * that the write goes out in one go, instead of two */
62 line
= strjoina(line
, "\n");
66 if (fputs(line
, f
) == EOF
)
70 if (fputc('\n', f
) == EOF
)
73 if (flags
& WRITE_STRING_FILE_SYNC
)
74 r
= fflush_sync_and_check(f
);
76 r
= fflush_and_check(f
);
81 struct timespec twice
[2] = {*ts
, *ts
};
83 if (futimens(fileno(f
), twice
) < 0)
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
| ((flags
& WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0));
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 write_string_filef(
206 WriteStringFileFlags flags
,
207 const char *format
, ...) {
209 _cleanup_free_
char *p
= NULL
;
213 va_start(ap
, format
);
214 r
= vasprintf(&p
, format
, ap
);
220 return write_string_file(fn
, p
, flags
);
223 int read_one_line_file(const char *fn
, char **line
) {
224 _cleanup_fclose_
FILE *f
= NULL
;
234 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
236 r
= read_line(f
, LONG_LINE_MAX
, line
);
237 return r
< 0 ? r
: 0;
240 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
241 _cleanup_fclose_
FILE *f
= NULL
;
242 _cleanup_free_
char *buf
= NULL
;
250 if (accept_extra_nl
&& endswith(blob
, "\n"))
251 accept_extra_nl
= false;
253 buf
= malloc(l
+ accept_extra_nl
+ 1);
261 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
263 /* We try to read one byte more than we need, so that we know whether we hit eof */
265 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
267 return errno
> 0 ? -errno
: -EIO
;
269 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
271 if (memcmp(buf
, blob
, l
) != 0)
273 if (k
> l
&& buf
[l
] != '\n')
279 int read_full_stream(FILE *f
, char **contents
, size_t *size
) {
280 _cleanup_free_
char *buf
= NULL
;
291 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
292 * optimize our buffering) */
294 if (fstat(fileno(f
), &st
) < 0)
297 if (S_ISREG(st
.st_mode
)) {
300 if (st
.st_size
> READ_FULL_BYTES_MAX
)
303 /* Start with the right file size, but be prepared for files from /proc which generally report a file
304 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
305 * already makes us notice the EOF. */
316 t
= realloc(buf
, n
+ 1);
322 k
= fread(buf
+ l
, 1, n
- l
, f
);
327 return errno
> 0 ? -errno
: -EIO
;
332 /* We aren't expecting fread() to return a short read outside
333 * of (error && eof), assert buffer is full and enlarge buffer.
338 if (n
>= READ_FULL_BYTES_MAX
)
341 n
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
345 *contents
= TAKE_PTR(buf
);
353 int read_full_file(const char *fn
, char **contents
, size_t *size
) {
354 _cleanup_fclose_
FILE *f
= NULL
;
363 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
365 return read_full_stream(f
, contents
, size
);
368 static int parse_env_file_internal(
371 int (*push
) (const char *filename
, unsigned line
,
372 const char *key
, char *value
, void *userdata
, int *n_pushed
),
376 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;
377 _cleanup_free_
char *contents
= NULL
, *key
= NULL
, *value
= NULL
;
389 SINGLE_QUOTE_VALUE_ESCAPE
,
391 DOUBLE_QUOTE_VALUE_ESCAPE
,
397 r
= read_full_stream(f
, &contents
, NULL
);
399 r
= read_full_file(fname
, &contents
, NULL
);
403 for (p
= contents
; *p
; p
++) {
409 if (strchr(COMMENTS
, c
))
411 else if (!strchr(WHITESPACE
, c
)) {
413 last_key_whitespace
= (size_t) -1;
415 if (!GREEDY_REALLOC(key
, key_alloc
, n_key
+2))
423 if (strchr(NEWLINE
, c
)) {
427 } else if (c
== '=') {
429 last_value_whitespace
= (size_t) -1;
431 if (!strchr(WHITESPACE
, c
))
432 last_key_whitespace
= (size_t) -1;
433 else if (last_key_whitespace
== (size_t) -1)
434 last_key_whitespace
= n_key
;
436 if (!GREEDY_REALLOC(key
, key_alloc
, n_key
+2))
445 if (strchr(NEWLINE
, c
)) {
453 /* strip trailing whitespace from key */
454 if (last_key_whitespace
!= (size_t) -1)
455 key
[last_key_whitespace
] = 0;
457 r
= push(fname
, line
, key
, value
, userdata
, n_pushed
);
463 value_alloc
= n_value
= 0;
465 } else if (c
== '\'')
466 state
= SINGLE_QUOTE_VALUE
;
468 state
= DOUBLE_QUOTE_VALUE
;
470 state
= VALUE_ESCAPE
;
471 else if (!strchr(WHITESPACE
, c
)) {
474 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
477 value
[n_value
++] = c
;
483 if (strchr(NEWLINE
, c
)) {
492 /* Chomp off trailing whitespace from value */
493 if (last_value_whitespace
!= (size_t) -1)
494 value
[last_value_whitespace
] = 0;
496 /* strip trailing whitespace from key */
497 if (last_key_whitespace
!= (size_t) -1)
498 key
[last_key_whitespace
] = 0;
500 r
= push(fname
, line
, key
, value
, userdata
, n_pushed
);
506 value_alloc
= n_value
= 0;
508 } else if (c
== '\\') {
509 state
= VALUE_ESCAPE
;
510 last_value_whitespace
= (size_t) -1;
512 if (!strchr(WHITESPACE
, c
))
513 last_value_whitespace
= (size_t) -1;
514 else if (last_value_whitespace
== (size_t) -1)
515 last_value_whitespace
= n_value
;
517 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
520 value
[n_value
++] = c
;
528 if (!strchr(NEWLINE
, c
)) {
529 /* Escaped newlines we eat up entirely */
530 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
533 value
[n_value
++] = c
;
537 case SINGLE_QUOTE_VALUE
:
541 state
= SINGLE_QUOTE_VALUE_ESCAPE
;
543 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
546 value
[n_value
++] = c
;
551 case SINGLE_QUOTE_VALUE_ESCAPE
:
552 state
= SINGLE_QUOTE_VALUE
;
554 if (!strchr(NEWLINE
, c
)) {
555 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
558 value
[n_value
++] = c
;
562 case DOUBLE_QUOTE_VALUE
:
566 state
= DOUBLE_QUOTE_VALUE_ESCAPE
;
568 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
571 value
[n_value
++] = c
;
576 case DOUBLE_QUOTE_VALUE_ESCAPE
:
577 state
= DOUBLE_QUOTE_VALUE
;
579 if (!strchr(NEWLINE
, c
)) {
580 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2))
583 value
[n_value
++] = c
;
589 state
= COMMENT_ESCAPE
;
590 else if (strchr(NEWLINE
, c
)) {
607 SINGLE_QUOTE_VALUE_ESCAPE
,
609 DOUBLE_QUOTE_VALUE_ESCAPE
)) {
617 if (last_value_whitespace
!= (size_t) -1)
618 value
[last_value_whitespace
] = 0;
620 /* strip trailing whitespace from key */
621 if (last_key_whitespace
!= (size_t) -1)
622 key
[last_key_whitespace
] = 0;
624 r
= push(fname
, line
, key
, value
, userdata
, n_pushed
);
634 static int check_utf8ness_and_warn(
635 const char *filename
, unsigned line
,
636 const char *key
, char *value
) {
638 if (!utf8_is_valid(key
)) {
639 _cleanup_free_
char *p
= NULL
;
641 p
= utf8_escape_invalid(key
);
642 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename
), line
, p
);
646 if (value
&& !utf8_is_valid(value
)) {
647 _cleanup_free_
char *p
= NULL
;
649 p
= utf8_escape_invalid(value
);
650 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename
), line
, key
, p
);
657 static int parse_env_file_push(
658 const char *filename
, unsigned line
,
659 const char *key
, char *value
,
664 va_list aq
, *ap
= userdata
;
667 r
= check_utf8ness_and_warn(filename
, line
, key
, value
);
673 while ((k
= va_arg(aq
, const char *))) {
676 v
= va_arg(aq
, char **);
705 r
= parse_env_file_internal(f
, fname
, parse_env_file_push
, &aq
, &n_pushed
);
722 r
= parse_env_filev(f
, fname
, ap
);
728 static int load_env_file_push(
729 const char *filename
, unsigned line
,
730 const char *key
, char *value
,
733 char ***m
= userdata
;
737 r
= check_utf8ness_and_warn(filename
, line
, key
, value
);
741 p
= strjoin(key
, "=", value
);
745 r
= strv_env_replace(m
, p
);
758 int load_env_file(FILE *f
, const char *fname
, char ***rl
) {
762 r
= parse_env_file_internal(f
, fname
, load_env_file_push
, &m
, NULL
);
772 static int load_env_file_push_pairs(
773 const char *filename
, unsigned line
,
774 const char *key
, char *value
,
777 char ***m
= userdata
;
780 r
= check_utf8ness_and_warn(filename
, line
, key
, value
);
784 r
= strv_extend(m
, key
);
789 r
= strv_extend(m
, "");
793 r
= strv_push(m
, value
);
804 int load_env_file_pairs(FILE *f
, const char *fname
, char ***rl
) {
808 r
= parse_env_file_internal(f
, fname
, load_env_file_push_pairs
, &m
, NULL
);
818 static int merge_env_file_push(
819 const char *filename
, unsigned line
,
820 const char *key
, char *value
,
824 char ***env
= userdata
;
825 char *expanded_value
;
830 log_error("%s:%u: invalid syntax (around \"%s\"), ignoring.", strna(filename
), line
, key
);
834 if (!env_name_is_valid(key
)) {
835 log_error("%s:%u: invalid variable name \"%s\", ignoring.", strna(filename
), line
, key
);
840 expanded_value
= replace_env(value
, *env
,
841 REPLACE_ENV_USE_ENVIRONMENT
|
842 REPLACE_ENV_ALLOW_BRACELESS
|
843 REPLACE_ENV_ALLOW_EXTENDED
);
847 free_and_replace(value
, expanded_value
);
849 return load_env_file_push(filename
, line
, key
, value
, env
, n_pushed
);
857 /* NOTE: this function supports braceful and braceless variable expansions,
858 * plus "extended" substitutions, unlike other exported parsing functions.
861 return parse_env_file_internal(f
, fname
, merge_env_file_push
, env
, NULL
);
864 static void write_env_var(FILE *f
, const char *v
) {
870 fputs_unlocked(v
, f
);
871 fputc_unlocked('\n', f
);
876 fwrite_unlocked(v
, 1, p
-v
, f
);
878 if (string_has_cc(p
, NULL
) || chars_intersect(p
, WHITESPACE SHELL_NEED_QUOTES
)) {
879 fputc_unlocked('\"', f
);
882 if (strchr(SHELL_NEED_ESCAPE
, *p
))
883 fputc_unlocked('\\', f
);
885 fputc_unlocked(*p
, f
);
888 fputc_unlocked('\"', f
);
890 fputs_unlocked(p
, f
);
892 fputc_unlocked('\n', f
);
895 int write_env_file(const char *fname
, char **l
) {
896 _cleanup_fclose_
FILE *f
= NULL
;
897 _cleanup_free_
char *p
= NULL
;
903 r
= fopen_temporary(fname
, &f
, &p
);
907 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
908 (void) fchmod_umask(fileno(f
), 0644);
911 write_env_var(f
, *i
);
913 r
= fflush_and_check(f
);
915 if (rename(p
, fname
) >= 0)
925 int executable_is_script(const char *path
, char **interpreter
) {
926 _cleanup_free_
char *line
= NULL
;
933 r
= read_one_line_file(path
, &line
);
934 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
939 if (!startswith(line
, "#!"))
942 ans
= strstrip(line
+ 2);
943 len
= strcspn(ans
, " \t");
948 ans
= strndup(ans
, len
);
957 * Retrieve one field from a file like /proc/self/status. pattern
958 * should not include whitespace or the delimiter (':'). pattern matches only
959 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
960 * zeros after the ':' will be skipped. field must be freed afterwards.
961 * terminator specifies the terminating characters of the field value (not
962 * included in the value).
964 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
965 _cleanup_free_
char *status
= NULL
;
975 r
= read_full_file(filename
, &status
, NULL
);
985 t
= strstr(t
, pattern
);
989 /* Check that pattern occurs in beginning of line. */
990 pattern_ok
= (t
== status
|| t
[-1] == '\n');
992 t
+= strlen(pattern
);
994 } while (!pattern_ok
);
996 t
+= strspn(t
, " \t");
1000 } while (*t
!= ':');
1005 t
+= strspn(t
, " \t");
1007 /* Also skip zeros, because when this is used for
1008 * capabilities, we don't want the zeros. This way the
1009 * same capability set always maps to the same string,
1010 * irrespective of the total capability set size. For
1011 * other numbers it shouldn't matter. */
1012 t
+= strspn(t
, "0");
1013 /* Back off one char if there's nothing but whitespace
1015 if (!*t
|| isspace(*t
))
1019 len
= strcspn(t
, terminator
);
1021 f
= strndup(t
, len
);
1029 DIR *xopendirat(int fd
, const char *name
, int flags
) {
1033 assert(!(flags
& O_CREAT
));
1035 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
1048 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
1055 if (!path_strv_resolve_uniq(search
, root
))
1058 STRV_FOREACH(i
, search
) {
1059 _cleanup_free_
char *p
= NULL
;
1063 p
= strjoin(root
, *i
, "/", path
);
1065 p
= strjoin(*i
, "/", path
);
1075 if (errno
!= ENOENT
)
1082 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
1083 _cleanup_strv_free_
char **copy
= NULL
;
1089 if (path_is_absolute(path
)) {
1092 f
= fopen(path
, mode
);
1101 copy
= strv_copy((char**) search
);
1105 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
1108 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
1109 _cleanup_strv_free_
char **s
= NULL
;
1111 if (path_is_absolute(path
)) {
1114 f
= fopen(path
, mode
);
1123 s
= strv_split_nulstr(search
);
1127 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
1130 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
1139 r
= tempfn_xxxxxx(path
, NULL
, &t
);
1143 fd
= mkostemp_safe(t
);
1149 f
= fdopen(fd
, "we");
1163 int fflush_and_check(FILE *f
) {
1170 return errno
> 0 ? -errno
: -EIO
;
1175 int fflush_sync_and_check(FILE *f
) {
1180 r
= fflush_and_check(f
);
1184 if (fsync(fileno(f
)) < 0)
1187 r
= fsync_directory_of_file(fileno(f
));
1194 /* This is much like mkostemp() but is subject to umask(). */
1195 int mkostemp_safe(char *pattern
) {
1196 _cleanup_umask_ mode_t u
= 0;
1203 fd
= mkostemp(pattern
, O_CLOEXEC
);
1210 int fmkostemp_safe(char *pattern
, const char *mode
, FILE **ret_f
) {
1214 fd
= mkostemp_safe(pattern
);
1218 f
= fdopen(fd
, mode
);
1228 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
1236 if (path_equal(p
, "/"))
1244 * /foo/bar/.#<extra>waldoXXXXXX
1248 if (!filename_is_valid(fn
))
1251 extra
= strempty(extra
);
1253 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
1257 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
1259 *ret
= path_simplify(t
, false);
1263 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
1273 if (path_equal(p
, "/"))
1281 * /foo/bar/.#<extra>waldobaa2a261115984a9
1285 if (!filename_is_valid(fn
))
1288 extra
= strempty(extra
);
1290 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
1294 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
1297 for (i
= 0; i
< 16; i
++) {
1298 *(x
++) = hexchar(u
& 0xF);
1304 *ret
= path_simplify(t
, false);
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);
1335 x
= stpcpy(stpcpy(t
, ".#"), extra
);
1337 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
1340 for (i
= 0; i
< 16; i
++) {
1341 *(x
++) = hexchar(u
& 0xF);
1347 *ret
= path_simplify(t
, false);
1351 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
1352 char ln
[DECIMAL_STR_MAX(n
)+2];
1354 /* Creates a "timestamp" file, that contains nothing but a
1355 * usec_t timestamp, formatted in ASCII. */
1357 if (n
<= 0 || n
>= USEC_INFINITY
)
1360 xsprintf(ln
, USEC_FMT
"\n", n
);
1362 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
1365 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
1366 _cleanup_free_
char *ln
= NULL
;
1370 r
= read_one_line_file(fn
, &ln
);
1374 r
= safe_atou64(ln
, &t
);
1378 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
1385 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
1390 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1391 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1392 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1393 * element, but not before the first one. */
1403 r
= fputs(separator
, f
);
1414 int open_tmpfile_unlinkable(const char *directory
, int flags
) {
1419 r
= tmp_dir(&directory
);
1422 } else if (isempty(directory
))
1425 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1427 /* Try O_TMPFILE first, if it is supported */
1428 fd
= open(directory
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
1432 /* Fall back to unguessable name + unlinking */
1433 p
= strjoina(directory
, "/systemd-tmp-XXXXXX");
1435 fd
= mkostemp_safe(p
);
1444 int open_tmpfile_linkable(const char *target
, int flags
, char **ret_path
) {
1445 _cleanup_free_
char *tmp
= NULL
;
1451 /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1452 assert((flags
& O_EXCL
) == 0);
1454 /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1455 * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1456 * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1458 fd
= open_parent(target
, O_TMPFILE
|flags
, 0640);
1464 log_debug_errno(fd
, "Failed to use O_TMPFILE for %s: %m", target
);
1466 r
= tempfn_random(target
, NULL
, &tmp
);
1470 fd
= open(tmp
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NOCTTY
|flags
, 0640);
1474 *ret_path
= TAKE_PTR(tmp
);
1479 int open_serialization_fd(const char *ident
) {
1482 fd
= memfd_create(ident
, MFD_CLOEXEC
);
1486 path
= getpid_cached() == 1 ? "/run/systemd" : "/tmp";
1487 fd
= open_tmpfile_unlinkable(path
, O_RDWR
|O_CLOEXEC
);
1491 log_debug("Serializing %s to %s.", ident
, path
);
1493 log_debug("Serializing %s to memfd.", ident
);
1498 int link_tmpfile(int fd
, const char *path
, const char *target
) {
1504 /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1505 * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1506 * on the directory, and renameat2() is used instead.
1508 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1509 * operation currently (renameat2() does), and there is no nice way to emulate this. */
1512 r
= rename_noreplace(AT_FDCWD
, path
, AT_FDCWD
, target
);
1516 char proc_fd_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(fd
) + 1];
1518 xsprintf(proc_fd_path
, "/proc/self/fd/%i", fd
);
1520 if (linkat(AT_FDCWD
, proc_fd_path
, AT_FDCWD
, target
, AT_SYMLINK_FOLLOW
) < 0)
1527 int read_nul_string(FILE *f
, char **ret
) {
1528 _cleanup_free_
char *x
= NULL
;
1529 size_t allocated
= 0, n
= 0;
1534 /* Reads a NUL-terminated string from the specified file. */
1539 if (!GREEDY_REALLOC(x
, allocated
, n
+2))
1543 if (c
== 0) /* Terminate at NUL byte */
1548 break; /* Terminate at EOF */
1567 int mkdtemp_malloc(const char *template, char **ret
) {
1568 _cleanup_free_
char *p
= NULL
;
1574 p
= strdup(template);
1582 p
= strjoin(tmp
, "/XXXXXX");
1594 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile
);
1596 int read_line(FILE *f
, size_t limit
, char **ret
) {
1597 _cleanup_free_
char *buffer
= NULL
;
1598 size_t n
= 0, allocated
= 0, count
= 0;
1602 /* Something like a bounded version of getline().
1604 * Considers EOF, \n and \0 end of line delimiters, and does not include these delimiters in the string
1607 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1608 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1610 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1611 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1613 * If a line shall be skipped ret may be initialized as NULL. */
1616 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
1621 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
1631 c
= fgetc_unlocked(f
);
1633 /* if we read an error, and have no data to return, then propagate the error */
1634 if (ferror_unlocked(f
) && n
== 0)
1635 return errno
> 0 ? -errno
: -EIO
;
1642 if (IN_SET(c
, '\n', 0)) /* Reached a delimiter */
1646 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
1649 buffer
[n
] = (char) c
;
1659 *ret
= TAKE_PTR(buffer
);