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 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
642 "%s:%u: invalid UTF-8 in key '%s', ignoring.",
643 strna(filename
), line
, p
);
646 if (value
&& !utf8_is_valid(value
)) {
647 _cleanup_free_
char *p
= NULL
;
649 p
= utf8_escape_invalid(value
);
650 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
651 "%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.",
652 strna(filename
), line
, key
, p
);
658 static int parse_env_file_push(
659 const char *filename
, unsigned line
,
660 const char *key
, char *value
,
665 va_list aq
, *ap
= userdata
;
668 r
= check_utf8ness_and_warn(filename
, line
, key
, value
);
674 while ((k
= va_arg(aq
, const char *))) {
677 v
= va_arg(aq
, char **);
706 r
= parse_env_file_internal(f
, fname
, parse_env_file_push
, &aq
, &n_pushed
);
714 int parse_env_file_sentinel(
723 r
= parse_env_filev(f
, fname
, ap
);
729 static int load_env_file_push(
730 const char *filename
, unsigned line
,
731 const char *key
, char *value
,
734 char ***m
= userdata
;
738 r
= check_utf8ness_and_warn(filename
, line
, key
, value
);
742 p
= strjoin(key
, "=", value
);
746 r
= strv_env_replace(m
, p
);
759 int load_env_file(FILE *f
, const char *fname
, char ***rl
) {
763 r
= parse_env_file_internal(f
, fname
, load_env_file_push
, &m
, NULL
);
773 static int load_env_file_push_pairs(
774 const char *filename
, unsigned line
,
775 const char *key
, char *value
,
778 char ***m
= userdata
;
781 r
= check_utf8ness_and_warn(filename
, line
, key
, value
);
785 r
= strv_extend(m
, key
);
790 r
= strv_extend(m
, "");
794 r
= strv_push(m
, value
);
805 int load_env_file_pairs(FILE *f
, const char *fname
, char ***rl
) {
809 r
= parse_env_file_internal(f
, fname
, load_env_file_push_pairs
, &m
, NULL
);
819 static int merge_env_file_push(
820 const char *filename
, unsigned line
,
821 const char *key
, char *value
,
825 char ***env
= userdata
;
826 char *expanded_value
;
831 log_error("%s:%u: invalid syntax (around \"%s\"), ignoring.", strna(filename
), line
, key
);
835 if (!env_name_is_valid(key
)) {
836 log_error("%s:%u: invalid variable name \"%s\", ignoring.", strna(filename
), line
, key
);
841 expanded_value
= replace_env(value
, *env
,
842 REPLACE_ENV_USE_ENVIRONMENT
|
843 REPLACE_ENV_ALLOW_BRACELESS
|
844 REPLACE_ENV_ALLOW_EXTENDED
);
848 free_and_replace(value
, expanded_value
);
850 return load_env_file_push(filename
, line
, key
, value
, env
, n_pushed
);
858 /* NOTE: this function supports braceful and braceless variable expansions,
859 * plus "extended" substitutions, unlike other exported parsing functions.
862 return parse_env_file_internal(f
, fname
, merge_env_file_push
, env
, NULL
);
865 static void write_env_var(FILE *f
, const char *v
) {
871 fputs_unlocked(v
, f
);
872 fputc_unlocked('\n', f
);
877 fwrite_unlocked(v
, 1, p
-v
, f
);
879 if (string_has_cc(p
, NULL
) || chars_intersect(p
, WHITESPACE SHELL_NEED_QUOTES
)) {
880 fputc_unlocked('\"', f
);
883 if (strchr(SHELL_NEED_ESCAPE
, *p
))
884 fputc_unlocked('\\', f
);
886 fputc_unlocked(*p
, f
);
889 fputc_unlocked('\"', f
);
891 fputs_unlocked(p
, f
);
893 fputc_unlocked('\n', f
);
896 int write_env_file(const char *fname
, char **l
) {
897 _cleanup_fclose_
FILE *f
= NULL
;
898 _cleanup_free_
char *p
= NULL
;
904 r
= fopen_temporary(fname
, &f
, &p
);
908 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
909 (void) fchmod_umask(fileno(f
), 0644);
912 write_env_var(f
, *i
);
914 r
= fflush_and_check(f
);
916 if (rename(p
, fname
) >= 0)
926 int executable_is_script(const char *path
, char **interpreter
) {
927 _cleanup_free_
char *line
= NULL
;
934 r
= read_one_line_file(path
, &line
);
935 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
940 if (!startswith(line
, "#!"))
943 ans
= strstrip(line
+ 2);
944 len
= strcspn(ans
, " \t");
949 ans
= strndup(ans
, len
);
958 * Retrieve one field from a file like /proc/self/status. pattern
959 * should not include whitespace or the delimiter (':'). pattern matches only
960 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
961 * zeros after the ':' will be skipped. field must be freed afterwards.
962 * terminator specifies the terminating characters of the field value (not
963 * included in the value).
965 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
966 _cleanup_free_
char *status
= NULL
;
976 r
= read_full_file(filename
, &status
, NULL
);
986 t
= strstr(t
, pattern
);
990 /* Check that pattern occurs in beginning of line. */
991 pattern_ok
= (t
== status
|| t
[-1] == '\n');
993 t
+= strlen(pattern
);
995 } while (!pattern_ok
);
997 t
+= strspn(t
, " \t");
1001 } while (*t
!= ':');
1006 t
+= strspn(t
, " \t");
1008 /* Also skip zeros, because when this is used for
1009 * capabilities, we don't want the zeros. This way the
1010 * same capability set always maps to the same string,
1011 * irrespective of the total capability set size. For
1012 * other numbers it shouldn't matter. */
1013 t
+= strspn(t
, "0");
1014 /* Back off one char if there's nothing but whitespace
1016 if (!*t
|| isspace(*t
))
1020 len
= strcspn(t
, terminator
);
1022 f
= strndup(t
, len
);
1030 DIR *xopendirat(int fd
, const char *name
, int flags
) {
1034 assert(!(flags
& O_CREAT
));
1036 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
1049 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
1056 if (!path_strv_resolve_uniq(search
, root
))
1059 STRV_FOREACH(i
, search
) {
1060 _cleanup_free_
char *p
= NULL
;
1064 p
= strjoin(root
, *i
, "/", path
);
1066 p
= strjoin(*i
, "/", path
);
1076 if (errno
!= ENOENT
)
1083 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
1084 _cleanup_strv_free_
char **copy
= NULL
;
1090 if (path_is_absolute(path
)) {
1093 f
= fopen(path
, mode
);
1102 copy
= strv_copy((char**) search
);
1106 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
1109 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
1110 _cleanup_strv_free_
char **s
= NULL
;
1112 if (path_is_absolute(path
)) {
1115 f
= fopen(path
, mode
);
1124 s
= strv_split_nulstr(search
);
1128 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
1131 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
1140 r
= tempfn_xxxxxx(path
, NULL
, &t
);
1144 fd
= mkostemp_safe(t
);
1150 f
= fdopen(fd
, "we");
1164 int fflush_and_check(FILE *f
) {
1171 return errno
> 0 ? -errno
: -EIO
;
1176 int fflush_sync_and_check(FILE *f
) {
1181 r
= fflush_and_check(f
);
1185 if (fsync(fileno(f
)) < 0)
1188 r
= fsync_directory_of_file(fileno(f
));
1195 /* This is much like mkostemp() but is subject to umask(). */
1196 int mkostemp_safe(char *pattern
) {
1197 _cleanup_umask_ mode_t u
= 0;
1204 fd
= mkostemp(pattern
, O_CLOEXEC
);
1211 int fmkostemp_safe(char *pattern
, const char *mode
, FILE **ret_f
) {
1215 fd
= mkostemp_safe(pattern
);
1219 f
= fdopen(fd
, mode
);
1229 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
1237 if (path_equal(p
, "/"))
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
) {
1274 if (path_equal(p
, "/"))
1282 * /foo/bar/.#<extra>waldobaa2a261115984a9
1286 if (!filename_is_valid(fn
))
1289 extra
= strempty(extra
);
1291 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
1295 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
1298 for (i
= 0; i
< 16; i
++) {
1299 *(x
++) = hexchar(u
& 0xF);
1305 *ret
= path_simplify(t
, false);
1309 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
1320 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1329 extra
= strempty(extra
);
1331 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
1336 x
= stpcpy(stpcpy(t
, ".#"), extra
);
1338 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
1341 for (i
= 0; i
< 16; i
++) {
1342 *(x
++) = hexchar(u
& 0xF);
1348 *ret
= path_simplify(t
, false);
1352 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
1353 char ln
[DECIMAL_STR_MAX(n
)+2];
1355 /* Creates a "timestamp" file, that contains nothing but a
1356 * usec_t timestamp, formatted in ASCII. */
1358 if (n
<= 0 || n
>= USEC_INFINITY
)
1361 xsprintf(ln
, USEC_FMT
"\n", n
);
1363 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
1366 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
1367 _cleanup_free_
char *ln
= NULL
;
1371 r
= read_one_line_file(fn
, &ln
);
1375 r
= safe_atou64(ln
, &t
);
1379 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
1386 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
1391 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1392 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1393 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1394 * element, but not before the first one. */
1404 r
= fputs(separator
, f
);
1415 int open_tmpfile_unlinkable(const char *directory
, int flags
) {
1420 r
= tmp_dir(&directory
);
1423 } else if (isempty(directory
))
1426 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1428 /* Try O_TMPFILE first, if it is supported */
1429 fd
= open(directory
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
1433 /* Fall back to unguessable name + unlinking */
1434 p
= strjoina(directory
, "/systemd-tmp-XXXXXX");
1436 fd
= mkostemp_safe(p
);
1445 int open_tmpfile_linkable(const char *target
, int flags
, char **ret_path
) {
1446 _cleanup_free_
char *tmp
= NULL
;
1452 /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1453 assert((flags
& O_EXCL
) == 0);
1455 /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1456 * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1457 * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1459 fd
= open_parent(target
, O_TMPFILE
|flags
, 0640);
1465 log_debug_errno(fd
, "Failed to use O_TMPFILE for %s: %m", target
);
1467 r
= tempfn_random(target
, NULL
, &tmp
);
1471 fd
= open(tmp
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NOCTTY
|flags
, 0640);
1475 *ret_path
= TAKE_PTR(tmp
);
1480 int open_serialization_fd(const char *ident
) {
1483 fd
= memfd_create(ident
, MFD_CLOEXEC
);
1487 path
= getpid_cached() == 1 ? "/run/systemd" : "/tmp";
1488 fd
= open_tmpfile_unlinkable(path
, O_RDWR
|O_CLOEXEC
);
1492 log_debug("Serializing %s to %s.", ident
, path
);
1494 log_debug("Serializing %s to memfd.", ident
);
1499 int link_tmpfile(int fd
, const char *path
, const char *target
) {
1505 /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1506 * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1507 * on the directory, and renameat2() is used instead.
1509 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1510 * operation currently (renameat2() does), and there is no nice way to emulate this. */
1513 r
= rename_noreplace(AT_FDCWD
, path
, AT_FDCWD
, target
);
1517 char proc_fd_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(fd
) + 1];
1519 xsprintf(proc_fd_path
, "/proc/self/fd/%i", fd
);
1521 if (linkat(AT_FDCWD
, proc_fd_path
, AT_FDCWD
, target
, AT_SYMLINK_FOLLOW
) < 0)
1528 int read_nul_string(FILE *f
, char **ret
) {
1529 _cleanup_free_
char *x
= NULL
;
1530 size_t allocated
= 0, n
= 0;
1535 /* Reads a NUL-terminated string from the specified file. */
1540 if (!GREEDY_REALLOC(x
, allocated
, n
+2))
1544 if (c
== 0) /* Terminate at NUL byte */
1549 break; /* Terminate at EOF */
1568 int mkdtemp_malloc(const char *template, char **ret
) {
1569 _cleanup_free_
char *p
= NULL
;
1575 p
= strdup(template);
1583 p
= strjoin(tmp
, "/XXXXXX");
1595 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile
);
1597 int read_line(FILE *f
, size_t limit
, char **ret
) {
1598 _cleanup_free_
char *buffer
= NULL
;
1599 size_t n
= 0, allocated
= 0, count
= 0;
1603 /* Something like a bounded version of getline().
1605 * Considers EOF, \n and \0 end of line delimiters, and does not include these delimiters in the string
1608 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1609 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1611 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1612 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1614 * If a line shall be skipped ret may be initialized as NULL. */
1617 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
1622 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
1632 c
= fgetc_unlocked(f
);
1634 /* if we read an error, and have no data to return, then propagate the error */
1635 if (ferror_unlocked(f
) && n
== 0)
1636 return errno
> 0 ? -errno
: -EIO
;
1643 if (IN_SET(c
, '\n', 0)) /* Reached a delimiter */
1647 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
1650 buffer
[n
] = (char) c
;
1660 *ret
= TAKE_PTR(buffer
);