]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/fileio.c
util: introduce memcmp_safe()
[thirdparty/systemd.git] / src / basic / fileio.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
a5c32cff 2
11c3a366
TA
3#include <errno.h>
4#include <fcntl.h>
5#include <limits.h>
6#include <stdarg.h>
7#include <stdint.h>
35bbbf85 8#include <stdio_ext.h>
11c3a366
TA
9#include <stdlib.h>
10#include <string.h>
7accca23 11#include <sys/mman.h>
11c3a366
TA
12#include <sys/stat.h>
13#include <sys/types.h>
a5c32cff 14#include <unistd.h>
cda134ab 15
b5efdb8a 16#include "alloc-util.h"
4f5dd394 17#include "ctype.h"
f4b51a2d 18#include "def.h"
99003e01 19#include "env-util.h"
4f5dd394 20#include "escape.h"
3ffd4af2
LP
21#include "fd-util.h"
22#include "fileio.h"
f4f15635 23#include "fs-util.h"
0d39fa9c 24#include "hexdecoct.h"
93cc7779
TA
25#include "log.h"
26#include "macro.h"
1d9ed171 27#include "missing.h"
33d52ab9 28#include "parse-util.h"
0d39fa9c 29#include "path-util.h"
df0ff127 30#include "process-util.h"
0d39fa9c 31#include "random-util.h"
33d52ab9 32#include "stdio-util.h"
07630cea 33#include "string-util.h"
a5c32cff 34#include "strv.h"
93cc7779 35#include "time-util.h"
affb60b1 36#include "umask-util.h"
335c46b5 37#include "utf8.h"
a5c32cff 38
c2d11a63
VC
39#define READ_FULL_BYTES_MAX (4U*1024U*1024U)
40
b1837133
LP
41int write_string_stream_ts(
42 FILE *f,
43 const char *line,
44 WriteStringFileFlags flags,
45 struct timespec *ts) {
dacd6cee 46
91dc2bf7 47 bool needs_nl;
be83711c 48 int r;
91dc2bf7 49
717603e3
LP
50 assert(f);
51 assert(line);
52
ba8b8c9e
MG
53 if (ferror(f))
54 return -EIO;
55
91dc2bf7
LP
56 needs_nl = !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) && !endswith(line, "\n");
57
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 */
61
62 line = strjoina(line, "\n");
63 needs_nl = false;
64 }
65
94d3b60f
MG
66 if (fputs(line, f) == EOF)
67 return -errno;
68
91dc2bf7 69 if (needs_nl)
94d3b60f
MG
70 if (fputc('\n', f) == EOF)
71 return -errno;
a5c32cff 72
be83711c
CL
73 if (flags & WRITE_STRING_FILE_SYNC)
74 r = fflush_sync_and_check(f);
75 else
76 r = fflush_and_check(f);
77 if (r < 0)
78 return r;
79
39c38d77
ZJS
80 if (ts) {
81 struct timespec twice[2] = {*ts, *ts};
82
83 if (futimens(fileno(f), twice) < 0)
84 return -errno;
85 }
86
be83711c 87 return 0;
a5c32cff
HH
88}
89
2eabcc77
LP
90static int write_string_file_atomic(
91 const char *fn,
92 const char *line,
b1837133 93 WriteStringFileFlags flags,
2eabcc77
LP
94 struct timespec *ts) {
95
a5c32cff
HH
96 _cleanup_fclose_ FILE *f = NULL;
97 _cleanup_free_ char *p = NULL;
98 int r;
99
100 assert(fn);
101 assert(line);
102
103 r = fopen_temporary(fn, &f, &p);
104 if (r < 0)
105 return r;
106
35bbbf85 107 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
0d39fa9c 108 (void) fchmod_umask(fileno(f), 0644);
a5c32cff 109
b1837133 110 r = write_string_stream_ts(f, line, flags, ts);
9dd1b1e8
LP
111 if (r < 0)
112 goto fail;
113
114 if (rename(p, fn) < 0) {
115 r = -errno;
116 goto fail;
a5c32cff
HH
117 }
118
9dd1b1e8 119 return 0;
a5c32cff 120
9dd1b1e8
LP
121fail:
122 (void) unlink(p);
a5c32cff
HH
123 return r;
124}
125
b1837133
LP
126int write_string_file_ts(
127 const char *fn,
128 const char *line,
129 WriteStringFileFlags flags,
130 struct timespec *ts) {
131
4c1fc3e4 132 _cleanup_fclose_ FILE *f = NULL;
eb3da901 133 int q, r;
4c1fc3e4
DM
134
135 assert(fn);
136 assert(line);
137
265710c2
AJ
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)));
0675e94a 140
4c1fc3e4
DM
141 if (flags & WRITE_STRING_FILE_ATOMIC) {
142 assert(flags & WRITE_STRING_FILE_CREATE);
143
b1837133 144 r = write_string_file_atomic(fn, line, flags, ts);
eb3da901
LP
145 if (r < 0)
146 goto fail;
147
148 return r;
39c38d77 149 } else
234519ae 150 assert(!ts);
4c1fc3e4
DM
151
152 if (flags & WRITE_STRING_FILE_CREATE) {
153 f = fopen(fn, "we");
eb3da901
LP
154 if (!f) {
155 r = -errno;
156 goto fail;
157 }
4c1fc3e4
DM
158 } else {
159 int fd;
160
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);
eb3da901
LP
164 if (fd < 0) {
165 r = -errno;
166 goto fail;
167 }
4c1fc3e4
DM
168
169 f = fdopen(fd, "we");
170 if (!f) {
eb3da901 171 r = -errno;
4c1fc3e4 172 safe_close(fd);
eb3da901 173 goto fail;
4c1fc3e4
DM
174 }
175 }
176
35bbbf85
LP
177 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
178
12ec9c30
TSH
179 if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
180 setvbuf(f, NULL, _IONBF, 0);
181
b1837133 182 r = write_string_stream_ts(f, line, flags, ts);
eb3da901
LP
183 if (r < 0)
184 goto fail;
185
186 return 0;
187
188fail:
189 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
190 return r;
191
192 f = safe_fclose(f);
193
194 /* OK, the operation failed, but let's see if the right
195 * contents in place already. If so, eat up the error. */
196
197 q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
198 if (q <= 0)
199 return r;
200
201 return 0;
4c1fc3e4
DM
202}
203
3130fca5
LP
204int write_string_filef(
205 const char *fn,
206 WriteStringFileFlags flags,
207 const char *format, ...) {
208
209 _cleanup_free_ char *p = NULL;
210 va_list ap;
211 int r;
212
213 va_start(ap, format);
214 r = vasprintf(&p, format, ap);
215 va_end(ap);
216
217 if (r < 0)
218 return -ENOMEM;
219
220 return write_string_file(fn, p, flags);
221}
222
a5c32cff
HH
223int read_one_line_file(const char *fn, char **line) {
224 _cleanup_fclose_ FILE *f = NULL;
2e33df93 225 int r;
a5c32cff
HH
226
227 assert(fn);
228 assert(line);
229
230 f = fopen(fn, "re");
231 if (!f)
232 return -errno;
233
35bbbf85
LP
234 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
235
2e33df93
ZJS
236 r = read_line(f, LONG_LINE_MAX, line);
237 return r < 0 ? r : 0;
a5c32cff
HH
238}
239
eb3da901
LP
240int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
241 _cleanup_fclose_ FILE *f = NULL;
242 _cleanup_free_ char *buf = NULL;
243 size_t l, k;
15dee3f0 244
eb3da901
LP
245 assert(fn);
246 assert(blob);
247
248 l = strlen(blob);
249
250 if (accept_extra_nl && endswith(blob, "\n"))
251 accept_extra_nl = false;
252
253 buf = malloc(l + accept_extra_nl + 1);
254 if (!buf)
255 return -ENOMEM;
256
257 f = fopen(fn, "re");
258 if (!f)
259 return -errno;
260
35bbbf85
LP
261 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
262
eb3da901
LP
263 /* We try to read one byte more than we need, so that we know whether we hit eof */
264 errno = 0;
265 k = fread(buf, 1, l + accept_extra_nl + 1, f);
266 if (ferror(f))
267 return errno > 0 ? -errno : -EIO;
268
269 if (k != l && k != l + accept_extra_nl)
270 return 0;
271 if (memcmp(buf, blob, l) != 0)
272 return 0;
273 if (k > l && buf[l] != '\n')
274 return 0;
15dee3f0 275
eb3da901 276 return 1;
15dee3f0
LP
277}
278
717603e3 279int read_full_stream(FILE *f, char **contents, size_t *size) {
a5c32cff
HH
280 _cleanup_free_ char *buf = NULL;
281 struct stat st;
c4054ddf
LP
282 size_t n, l;
283 int fd;
a5c32cff 284
717603e3 285 assert(f);
a5c32cff
HH
286 assert(contents);
287
717603e3 288 n = LINE_MAX;
a5c32cff 289
c4054ddf
LP
290 fd = fileno(f);
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) */
717603e3 293
c4054ddf
LP
294 if (fstat(fileno(f), &st) < 0)
295 return -errno;
296
297 if (S_ISREG(st.st_mode)) {
717603e3 298
c4054ddf
LP
299 /* Safety check */
300 if (st.st_size > READ_FULL_BYTES_MAX)
301 return -E2BIG;
302
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. */
306 if (st.st_size > 0)
307 n = st.st_size + 1;
308 }
717603e3 309 }
a5c32cff 310
717603e3 311 l = 0;
a5c32cff
HH
312 for (;;) {
313 char *t;
314 size_t k;
315
c2d11a63 316 t = realloc(buf, n + 1);
a5c32cff
HH
317 if (!t)
318 return -ENOMEM;
319
320 buf = t;
5a89faf0 321 errno = 0;
a5c32cff 322 k = fread(buf + l, 1, n - l, f);
c2d11a63
VC
323 if (k > 0)
324 l += k;
a5c32cff 325
c2d11a63 326 if (ferror(f))
5a89faf0 327 return errno > 0 ? -errno : -EIO;
a5c32cff 328
c2d11a63 329 if (feof(f))
a5c32cff 330 break;
a5c32cff 331
c2d11a63
VC
332 /* We aren't expecting fread() to return a short read outside
333 * of (error && eof), assert buffer is full and enlarge buffer.
334 */
335 assert(l == n);
a5c32cff
HH
336
337 /* Safety check */
c2d11a63 338 if (n >= READ_FULL_BYTES_MAX)
a5c32cff 339 return -E2BIG;
c2d11a63 340
82b103a7 341 n = MIN(n * 2, READ_FULL_BYTES_MAX);
a5c32cff
HH
342 }
343
344 buf[l] = 0;
ae2a15bc 345 *contents = TAKE_PTR(buf);
a5c32cff
HH
346
347 if (size)
348 *size = l;
349
350 return 0;
351}
352
717603e3
LP
353int read_full_file(const char *fn, char **contents, size_t *size) {
354 _cleanup_fclose_ FILE *f = NULL;
355
356 assert(fn);
357 assert(contents);
358
359 f = fopen(fn, "re");
360 if (!f)
361 return -errno;
362
35bbbf85
LP
363 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
364
717603e3
LP
365 return read_full_stream(f, contents, size);
366}
367
f73141d7 368static int parse_env_file_internal(
717603e3 369 FILE *f,
a5c32cff 370 const char *fname,
f73141d7 371 const char *newline,
335c46b5 372 int (*push) (const char *filename, unsigned line,
a5f6c30d
MS
373 const char *key, char *value, void *userdata, int *n_pushed),
374 void *userdata,
375 int *n_pushed) {
f73141d7 376
2b77f67e 377 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;
d56fced9 378 _cleanup_free_ char *contents = NULL, *key = NULL, *value = NULL;
335c46b5 379 unsigned line = 1;
d56fced9
LP
380 char *p;
381 int r;
a5c32cff 382
f73141d7
LP
383 enum {
384 PRE_KEY,
385 KEY,
f73141d7
LP
386 PRE_VALUE,
387 VALUE,
388 VALUE_ESCAPE,
389 SINGLE_QUOTE_VALUE,
390 SINGLE_QUOTE_VALUE_ESCAPE,
391 DOUBLE_QUOTE_VALUE,
392 DOUBLE_QUOTE_VALUE_ESCAPE,
393 COMMENT,
394 COMMENT_ESCAPE
395 } state = PRE_KEY;
a5c32cff 396
f73141d7 397 assert(newline);
a5c32cff 398
717603e3
LP
399 if (f)
400 r = read_full_stream(f, &contents, NULL);
401 else
402 r = read_full_file(fname, &contents, NULL);
1c17cbed 403 if (r < 0)
a5c32cff
HH
404 return r;
405
f73141d7
LP
406 for (p = contents; *p; p++) {
407 char c = *p;
408
409 switch (state) {
410
411 case PRE_KEY:
ebc05a09 412 if (strchr(COMMENTS, c))
f73141d7
LP
413 state = COMMENT;
414 else if (!strchr(WHITESPACE, c)) {
415 state = KEY;
2b77f67e
LP
416 last_key_whitespace = (size_t) -1;
417
d56fced9
LP
418 if (!GREEDY_REALLOC(key, key_alloc, n_key+2))
419 return -ENOMEM;
f73141d7
LP
420
421 key[n_key++] = c;
422 }
423 break;
424
425 case KEY:
426 if (strchr(newline, c)) {
427 state = PRE_KEY;
313cefa1 428 line++;
f73141d7 429 n_key = 0;
2b77f67e 430 } else if (c == '=') {
f73141d7 431 state = PRE_VALUE;
2b77f67e
LP
432 last_value_whitespace = (size_t) -1;
433 } else {
434 if (!strchr(WHITESPACE, c))
435 last_key_whitespace = (size_t) -1;
436 else if (last_key_whitespace == (size_t) -1)
437 last_key_whitespace = n_key;
438
d56fced9
LP
439 if (!GREEDY_REALLOC(key, key_alloc, n_key+2))
440 return -ENOMEM;
f73141d7
LP
441
442 key[n_key++] = c;
443 }
a5c32cff 444
f73141d7
LP
445 break;
446
f73141d7 447 case PRE_VALUE:
98f59e59 448 if (strchr(newline, c)) {
f73141d7 449 state = PRE_KEY;
313cefa1 450 line++;
f73141d7 451 key[n_key] = 0;
a5c32cff 452
f73141d7
LP
453 if (value)
454 value[n_value] = 0;
a5c32cff 455
ebc05a09 456 /* strip trailing whitespace from key */
2b77f67e
LP
457 if (last_key_whitespace != (size_t) -1)
458 key[last_key_whitespace] = 0;
ebc05a09 459
a5f6c30d 460 r = push(fname, line, key, value, userdata, n_pushed);
f73141d7 461 if (r < 0)
d56fced9 462 return r;
f73141d7
LP
463
464 n_key = 0;
465 value = NULL;
466 value_alloc = n_value = 0;
2b77f67e 467
f73141d7
LP
468 } else if (c == '\'')
469 state = SINGLE_QUOTE_VALUE;
470 else if (c == '\"')
471 state = DOUBLE_QUOTE_VALUE;
472 else if (c == '\\')
473 state = VALUE_ESCAPE;
474 else if (!strchr(WHITESPACE, c)) {
475 state = VALUE;
476
d56fced9
LP
477 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
478 return -ENOMEM;
f73141d7
LP
479
480 value[n_value++] = c;
481 }
482
483 break;
484
485 case VALUE:
486 if (strchr(newline, c)) {
487 state = PRE_KEY;
313cefa1 488 line++;
98f59e59 489
f73141d7
LP
490 key[n_key] = 0;
491
492 if (value)
493 value[n_value] = 0;
494
2b77f67e
LP
495 /* Chomp off trailing whitespace from value */
496 if (last_value_whitespace != (size_t) -1)
497 value[last_value_whitespace] = 0;
f73141d7 498
ebc05a09 499 /* strip trailing whitespace from key */
2b77f67e
LP
500 if (last_key_whitespace != (size_t) -1)
501 key[last_key_whitespace] = 0;
ebc05a09 502
a5f6c30d 503 r = push(fname, line, key, value, userdata, n_pushed);
f73141d7 504 if (r < 0)
d56fced9 505 return r;
f73141d7
LP
506
507 n_key = 0;
508 value = NULL;
509 value_alloc = n_value = 0;
2b77f67e 510
f73141d7
LP
511 } else if (c == '\\') {
512 state = VALUE_ESCAPE;
2b77f67e 513 last_value_whitespace = (size_t) -1;
f73141d7
LP
514 } else {
515 if (!strchr(WHITESPACE, c))
2b77f67e
LP
516 last_value_whitespace = (size_t) -1;
517 else if (last_value_whitespace == (size_t) -1)
518 last_value_whitespace = n_value;
f73141d7 519
d56fced9
LP
520 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
521 return -ENOMEM;
f73141d7
LP
522
523 value[n_value++] = c;
524 }
525
526 break;
527
528 case VALUE_ESCAPE:
529 state = VALUE;
530
531 if (!strchr(newline, c)) {
532 /* Escaped newlines we eat up entirely */
d56fced9
LP
533 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
534 return -ENOMEM;
f73141d7
LP
535
536 value[n_value++] = c;
537 }
538 break;
539
540 case SINGLE_QUOTE_VALUE:
541 if (c == '\'')
542 state = PRE_VALUE;
543 else if (c == '\\')
544 state = SINGLE_QUOTE_VALUE_ESCAPE;
545 else {
d56fced9
LP
546 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
547 return -ENOMEM;
a5c32cff 548
f73141d7
LP
549 value[n_value++] = c;
550 }
a5c32cff 551
f73141d7 552 break;
a5c32cff 553
f73141d7
LP
554 case SINGLE_QUOTE_VALUE_ESCAPE:
555 state = SINGLE_QUOTE_VALUE;
a5c32cff 556
f73141d7 557 if (!strchr(newline, c)) {
d56fced9
LP
558 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
559 return -ENOMEM;
a5c32cff 560
f73141d7
LP
561 value[n_value++] = c;
562 }
563 break;
564
565 case DOUBLE_QUOTE_VALUE:
566 if (c == '\"')
567 state = PRE_VALUE;
568 else if (c == '\\')
569 state = DOUBLE_QUOTE_VALUE_ESCAPE;
570 else {
d56fced9
LP
571 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
572 return -ENOMEM;
a5c32cff 573
f73141d7
LP
574 value[n_value++] = c;
575 }
576
577 break;
578
579 case DOUBLE_QUOTE_VALUE_ESCAPE:
580 state = DOUBLE_QUOTE_VALUE;
a5c32cff 581
f73141d7 582 if (!strchr(newline, c)) {
d56fced9
LP
583 if (!GREEDY_REALLOC(value, value_alloc, n_value+2))
584 return -ENOMEM;
a5c32cff 585
f73141d7 586 value[n_value++] = c;
a5c32cff 587 }
f73141d7
LP
588 break;
589
590 case COMMENT:
591 if (c == '\\')
592 state = COMMENT_ESCAPE;
335c46b5 593 else if (strchr(newline, c)) {
f73141d7 594 state = PRE_KEY;
313cefa1 595 line++;
335c46b5 596 }
f73141d7
LP
597 break;
598
599 case COMMENT_ESCAPE:
600 state = COMMENT;
601 break;
a5c32cff 602 }
f73141d7
LP
603 }
604
371328dc
ZJS
605 if (IN_SET(state,
606 PRE_VALUE,
607 VALUE,
608 VALUE_ESCAPE,
609 SINGLE_QUOTE_VALUE,
610 SINGLE_QUOTE_VALUE_ESCAPE,
611 DOUBLE_QUOTE_VALUE,
612 DOUBLE_QUOTE_VALUE_ESCAPE)) {
a5c32cff 613
f73141d7
LP
614 key[n_key] = 0;
615
616 if (value)
617 value[n_value] = 0;
618
2b77f67e
LP
619 if (state == VALUE)
620 if (last_value_whitespace != (size_t) -1)
621 value[last_value_whitespace] = 0;
622
ebc05a09 623 /* strip trailing whitespace from key */
2b77f67e
LP
624 if (last_key_whitespace != (size_t) -1)
625 key[last_key_whitespace] = 0;
ebc05a09 626
a5f6c30d 627 r = push(fname, line, key, value, userdata, n_pushed);
f73141d7 628 if (r < 0)
d56fced9
LP
629 return r;
630
631 value = NULL;
a5c32cff
HH
632 }
633
f73141d7 634 return 0;
a5c32cff
HH
635}
636
ac466818 637static int check_utf8ness_and_warn(
717603e3 638 const char *filename, unsigned line,
ac466818 639 const char *key, char *value) {
f27f0e21
GB
640
641 if (!utf8_is_valid(key)) {
3587161a 642 _cleanup_free_ char *p = NULL;
550a40ec 643
717603e3
LP
644 p = utf8_escape_invalid(key);
645 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p);
f27f0e21
GB
646 return -EINVAL;
647 }
648
649 if (value && !utf8_is_valid(value)) {
3587161a 650 _cleanup_free_ char *p = NULL;
550a40ec 651
717603e3
LP
652 p = utf8_escape_invalid(value);
653 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, p);
f27f0e21
GB
654 return -EINVAL;
655 }
a5c32cff 656
ac466818
ZJS
657 return 0;
658}
659
660static int parse_env_file_push(
661 const char *filename, unsigned line,
662 const char *key, char *value,
663 void *userdata,
664 int *n_pushed) {
665
666 const char *k;
667 va_list aq, *ap = userdata;
668 int r;
669
670 r = check_utf8ness_and_warn(filename, line, key, value);
671 if (r < 0)
672 return r;
673
f27f0e21 674 va_copy(aq, *ap);
a5c32cff 675
f27f0e21
GB
676 while ((k = va_arg(aq, const char *))) {
677 char **v;
a5c32cff 678
f27f0e21 679 v = va_arg(aq, char **);
a5c32cff 680
f27f0e21
GB
681 if (streq(key, k)) {
682 va_end(aq);
683 free(*v);
684 *v = value;
a5f6c30d
MS
685
686 if (n_pushed)
687 (*n_pushed)++;
688
f27f0e21 689 return 1;
f73141d7 690 }
335c46b5 691 }
a5c32cff 692
f27f0e21 693 va_end(aq);
f73141d7 694 free(value);
717603e3 695
f73141d7
LP
696 return 0;
697}
a5c32cff 698
080dfda8 699int parse_env_filev(
1a5a177e 700 FILE *f,
f73141d7 701 const char *fname,
080dfda8
LP
702 const char *newline,
703 va_list ap) {
a5c32cff 704
a5f6c30d 705 int r, n_pushed = 0;
080dfda8 706 va_list aq;
a5c32cff 707
f73141d7
LP
708 if (!newline)
709 newline = NEWLINE;
a5c32cff 710
080dfda8
LP
711 va_copy(aq, ap);
712 r = parse_env_file_internal(f, fname, newline, parse_env_file_push, &aq, &n_pushed);
713 va_end(aq);
714 if (r < 0)
715 return r;
716
717 return n_pushed;
718}
719
720int parse_env_file(
721 FILE *f,
722 const char *fname,
723 const char *newline,
724 ...) {
725
726 va_list ap;
727 int r;
728
f73141d7 729 va_start(ap, newline);
080dfda8 730 r = parse_env_filev(f, fname, newline, ap);
f73141d7 731 va_end(ap);
a5c32cff 732
080dfda8 733 return r;
f73141d7 734}
a5c32cff 735
717603e3
LP
736static int load_env_file_push(
737 const char *filename, unsigned line,
738 const char *key, char *value,
a5f6c30d
MS
739 void *userdata,
740 int *n_pushed) {
f27f0e21
GB
741 char ***m = userdata;
742 char *p;
743 int r;
a5c32cff 744
ac466818
ZJS
745 r = check_utf8ness_and_warn(filename, line, key, value);
746 if (r < 0)
747 return r;
a5c32cff 748
99003e01 749 p = strjoin(key, "=", value);
f27f0e21
GB
750 if (!p)
751 return -ENOMEM;
335c46b5 752
99003e01
ZJS
753 r = strv_env_replace(m, p);
754 if (r < 0) {
755 free(p);
f27f0e21 756 return r;
99003e01 757 }
a5c32cff 758
a5f6c30d
MS
759 if (n_pushed)
760 (*n_pushed)++;
761
f73141d7
LP
762 free(value);
763 return 0;
764}
765
717603e3
LP
766int load_env_file(FILE *f, const char *fname, const char *newline, char ***rl) {
767 char **m = NULL;
768 int r;
769
770 if (!newline)
771 newline = NEWLINE;
772
a5f6c30d 773 r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
717603e3
LP
774 if (r < 0) {
775 strv_free(m);
776 return r;
777 }
778
779 *rl = m;
780 return 0;
781}
782
783static int load_env_file_push_pairs(
784 const char *filename, unsigned line,
785 const char *key, char *value,
a5f6c30d
MS
786 void *userdata,
787 int *n_pushed) {
717603e3
LP
788 char ***m = userdata;
789 int r;
790
ac466818
ZJS
791 r = check_utf8ness_and_warn(filename, line, key, value);
792 if (r < 0)
793 return r;
717603e3
LP
794
795 r = strv_extend(m, key);
796 if (r < 0)
797 return -ENOMEM;
798
799 if (!value) {
800 r = strv_extend(m, "");
801 if (r < 0)
802 return -ENOMEM;
803 } else {
804 r = strv_push(m, value);
805 if (r < 0)
806 return r;
807 }
808
a5f6c30d
MS
809 if (n_pushed)
810 (*n_pushed)++;
811
717603e3
LP
812 return 0;
813}
814
815int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
f73141d7
LP
816 char **m = NULL;
817 int r;
a5c32cff 818
f73141d7
LP
819 if (!newline)
820 newline = NEWLINE;
821
a5f6c30d 822 r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
f73141d7
LP
823 if (r < 0) {
824 strv_free(m);
825 return r;
a5c32cff
HH
826 }
827
828 *rl = m;
a5c32cff
HH
829 return 0;
830}
831
37f3ffca
RS
832static int merge_env_file_push(
833 const char *filename, unsigned line,
834 const char *key, char *value,
835 void *userdata,
836 int *n_pushed) {
837
838 char ***env = userdata;
839 char *expanded_value;
840
841 assert(env);
842
184d1904
ZJS
843 if (!value) {
844 log_error("%s:%u: invalid syntax (around \"%s\"), ignoring.", strna(filename), line, key);
845 return 0;
846 }
847
848 if (!env_name_is_valid(key)) {
849 log_error("%s:%u: invalid variable name \"%s\", ignoring.", strna(filename), line, key);
2ea8081a 850 free(value);
184d1904
ZJS
851 return 0;
852 }
853
ccad1fd0 854 expanded_value = replace_env(value, *env,
b82f58bf
RS
855 REPLACE_ENV_USE_ENVIRONMENT|
856 REPLACE_ENV_ALLOW_BRACELESS|
857 REPLACE_ENV_ALLOW_EXTENDED);
37f3ffca
RS
858 if (!expanded_value)
859 return -ENOMEM;
860
861 free_and_replace(value, expanded_value);
862
863 return load_env_file_push(filename, line, key, value, env, n_pushed);
864}
865
866int merge_env_file(
867 char ***env,
868 FILE *f,
869 const char *fname) {
870
ccad1fd0 871 /* NOTE: this function supports braceful and braceless variable expansions,
b82f58bf 872 * plus "extended" substitutions, unlike other exported parsing functions.
ccad1fd0
ZJS
873 */
874
37f3ffca
RS
875 return parse_env_file_internal(f, fname, NEWLINE, merge_env_file_push, env, NULL);
876}
877
768100ef
LP
878static void write_env_var(FILE *f, const char *v) {
879 const char *p;
880
881 p = strchr(v, '=');
882 if (!p) {
883 /* Fallback */
4b61c875
LP
884 fputs_unlocked(v, f);
885 fputc_unlocked('\n', f);
768100ef
LP
886 return;
887 }
888
889 p++;
4b61c875 890 fwrite_unlocked(v, 1, p-v, f);
768100ef 891
0ce5a806 892 if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
4b61c875 893 fputc_unlocked('\"', f);
768100ef
LP
894
895 for (; *p; p++) {
0ce5a806 896 if (strchr(SHELL_NEED_ESCAPE, *p))
4b61c875 897 fputc_unlocked('\\', f);
768100ef 898
4b61c875 899 fputc_unlocked(*p, f);
768100ef
LP
900 }
901
4b61c875 902 fputc_unlocked('\"', f);
768100ef 903 } else
4b61c875 904 fputs_unlocked(p, f);
768100ef 905
4b61c875 906 fputc_unlocked('\n', f);
768100ef
LP
907}
908
a5c32cff 909int write_env_file(const char *fname, char **l) {
7fd1b19b 910 _cleanup_fclose_ FILE *f = NULL;
736937e5
LP
911 _cleanup_free_ char *p = NULL;
912 char **i;
a5c32cff
HH
913 int r;
914
736937e5
LP
915 assert(fname);
916
a5c32cff
HH
917 r = fopen_temporary(fname, &f, &p);
918 if (r < 0)
919 return r;
920
35bbbf85
LP
921 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
922 (void) fchmod_umask(fileno(f), 0644);
a5c32cff 923
768100ef
LP
924 STRV_FOREACH(i, l)
925 write_env_var(f, *i);
a5c32cff 926
736937e5
LP
927 r = fflush_and_check(f);
928 if (r >= 0) {
929 if (rename(p, fname) >= 0)
930 return 0;
a5c32cff 931
736937e5 932 r = -errno;
a5c32cff
HH
933 }
934
736937e5 935 unlink(p);
a5c32cff
HH
936 return r;
937}
68fee104
ZJS
938
939int executable_is_script(const char *path, char **interpreter) {
c8b32e11 940 _cleanup_free_ char *line = NULL;
99c61f6b 941 size_t len;
68fee104 942 char *ans;
99c61f6b 943 int r;
68fee104
ZJS
944
945 assert(path);
946
947 r = read_one_line_file(path, &line);
99c61f6b
LP
948 if (r == -ENOBUFS) /* First line overly long? if so, then it's not a script */
949 return 0;
68fee104
ZJS
950 if (r < 0)
951 return r;
952
953 if (!startswith(line, "#!"))
954 return 0;
955
956 ans = strstrip(line + 2);
957 len = strcspn(ans, " \t");
958
959 if (len == 0)
960 return 0;
961
962 ans = strndup(ans, len);
963 if (!ans)
964 return -ENOMEM;
965
966 *interpreter = ans;
967 return 1;
968}
69ab8088
ZJS
969
970/**
0a7b53bd 971 * Retrieve one field from a file like /proc/self/status. pattern
c4cd1d4d
AK
972 * should not include whitespace or the delimiter (':'). pattern matches only
973 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
974 * zeros after the ':' will be skipped. field must be freed afterwards.
975 * terminator specifies the terminating characters of the field value (not
976 * included in the value).
69ab8088 977 */
c4cd1d4d 978int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
69ab8088 979 _cleanup_free_ char *status = NULL;
90110825 980 char *t, *f;
69ab8088
ZJS
981 size_t len;
982 int r;
983
c4cd1d4d 984 assert(terminator);
69ab8088 985 assert(filename);
7ff7394d 986 assert(pattern);
69ab8088
ZJS
987 assert(field);
988
989 r = read_full_file(filename, &status, NULL);
990 if (r < 0)
991 return r;
992
c4cd1d4d
AK
993 t = status;
994
995 do {
996 bool pattern_ok;
997
998 do {
999 t = strstr(t, pattern);
1000 if (!t)
1001 return -ENOENT;
1002
1003 /* Check that pattern occurs in beginning of line. */
1004 pattern_ok = (t == status || t[-1] == '\n');
1005
1006 t += strlen(pattern);
1007
1008 } while (!pattern_ok);
1009
1010 t += strspn(t, " \t");
1011 if (!*t)
1012 return -ENOENT;
1013
1014 } while (*t != ':');
1015
1016 t++;
69ab8088 1017
4ec29144 1018 if (*t) {
1e5413f7
ZJS
1019 t += strspn(t, " \t");
1020
1021 /* Also skip zeros, because when this is used for
1022 * capabilities, we don't want the zeros. This way the
1023 * same capability set always maps to the same string,
1024 * irrespective of the total capability set size. For
1025 * other numbers it shouldn't matter. */
1026 t += strspn(t, "0");
4ec29144
ZJS
1027 /* Back off one char if there's nothing but whitespace
1028 and zeros */
1e5413f7 1029 if (!*t || isspace(*t))
313cefa1 1030 t--;
4ec29144 1031 }
69ab8088 1032
c4cd1d4d 1033 len = strcspn(t, terminator);
69ab8088 1034
90110825
LP
1035 f = strndup(t, len);
1036 if (!f)
69ab8088
ZJS
1037 return -ENOMEM;
1038
90110825 1039 *field = f;
69ab8088
ZJS
1040 return 0;
1041}
0d39fa9c
LP
1042
1043DIR *xopendirat(int fd, const char *name, int flags) {
1044 int nfd;
1045 DIR *d;
1046
1047 assert(!(flags & O_CREAT));
1048
1049 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
1050 if (nfd < 0)
1051 return NULL;
1052
1053 d = fdopendir(nfd);
1054 if (!d) {
1055 safe_close(nfd);
1056 return NULL;
1057 }
1058
1059 return d;
1060}
1061
1062static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
1063 char **i;
1064
1065 assert(path);
1066 assert(mode);
1067 assert(_f);
1068
1069 if (!path_strv_resolve_uniq(search, root))
1070 return -ENOMEM;
1071
1072 STRV_FOREACH(i, search) {
1073 _cleanup_free_ char *p = NULL;
1074 FILE *f;
1075
1076 if (root)
605405c6 1077 p = strjoin(root, *i, "/", path);
0d39fa9c 1078 else
605405c6 1079 p = strjoin(*i, "/", path);
0d39fa9c
LP
1080 if (!p)
1081 return -ENOMEM;
1082
1083 f = fopen(p, mode);
1084 if (f) {
1085 *_f = f;
1086 return 0;
1087 }
1088
1089 if (errno != ENOENT)
1090 return -errno;
1091 }
1092
1093 return -ENOENT;
1094}
1095
1096int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
1097 _cleanup_strv_free_ char **copy = NULL;
1098
1099 assert(path);
1100 assert(mode);
1101 assert(_f);
1102
1103 if (path_is_absolute(path)) {
1104 FILE *f;
1105
1106 f = fopen(path, mode);
1107 if (f) {
1108 *_f = f;
1109 return 0;
1110 }
1111
1112 return -errno;
1113 }
1114
1115 copy = strv_copy((char**) search);
1116 if (!copy)
1117 return -ENOMEM;
1118
1119 return search_and_fopen_internal(path, mode, root, copy, _f);
1120}
1121
1122int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
1123 _cleanup_strv_free_ char **s = NULL;
1124
1125 if (path_is_absolute(path)) {
1126 FILE *f;
1127
1128 f = fopen(path, mode);
1129 if (f) {
1130 *_f = f;
1131 return 0;
1132 }
1133
1134 return -errno;
1135 }
1136
1137 s = strv_split_nulstr(search);
1138 if (!s)
1139 return -ENOMEM;
1140
1141 return search_and_fopen_internal(path, mode, root, s, _f);
1142}
1143
1144int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1145 FILE *f;
1146 char *t;
1147 int r, fd;
1148
1149 assert(path);
1150 assert(_f);
1151 assert(_temp_path);
1152
1153 r = tempfn_xxxxxx(path, NULL, &t);
1154 if (r < 0)
1155 return r;
1156
646853bd 1157 fd = mkostemp_safe(t);
0d39fa9c
LP
1158 if (fd < 0) {
1159 free(t);
1160 return -errno;
1161 }
1162
1163 f = fdopen(fd, "we");
1164 if (!f) {
1165 unlink_noerrno(t);
1166 free(t);
1167 safe_close(fd);
1168 return -errno;
1169 }
1170
1171 *_f = f;
1172 *_temp_path = t;
1173
1174 return 0;
1175}
1176
1177int fflush_and_check(FILE *f) {
1178 assert(f);
1179
1180 errno = 0;
1181 fflush(f);
1182
1183 if (ferror(f))
f5e5c28f 1184 return errno > 0 ? -errno : -EIO;
0d39fa9c
LP
1185
1186 return 0;
1187}
1188
0675e94a
AJ
1189int fflush_sync_and_check(FILE *f) {
1190 int r;
1191
1192 assert(f);
1193
1194 r = fflush_and_check(f);
1195 if (r < 0)
1196 return r;
1197
1198 if (fsync(fileno(f)) < 0)
1199 return -errno;
1200
8ac2f74f
LP
1201 r = fsync_directory_of_file(fileno(f));
1202 if (r < 0)
1203 return r;
1204
0675e94a
AJ
1205 return 0;
1206}
1207
61233823 1208/* This is much like mkostemp() but is subject to umask(). */
646853bd 1209int mkostemp_safe(char *pattern) {
3587161a 1210 _cleanup_umask_ mode_t u = 0;
0d39fa9c
LP
1211 int fd;
1212
1213 assert(pattern);
1214
1215 u = umask(077);
1216
646853bd 1217 fd = mkostemp(pattern, O_CLOEXEC);
0d39fa9c
LP
1218 if (fd < 0)
1219 return -errno;
1220
1221 return fd;
1222}
1223
0d39fa9c
LP
1224int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1225 const char *fn;
1226 char *t;
1227
0d39fa9c
LP
1228 assert(ret);
1229
09942654
LP
1230 if (isempty(p))
1231 return -EINVAL;
1232 if (path_equal(p, "/"))
1233 return -EINVAL;
1234
0d39fa9c
LP
1235 /*
1236 * Turns this:
1237 * /foo/bar/waldo
1238 *
1239 * Into this:
1240 * /foo/bar/.#<extra>waldoXXXXXX
1241 */
1242
1243 fn = basename(p);
1244 if (!filename_is_valid(fn))
1245 return -EINVAL;
1246
ad5d4b17 1247 extra = strempty(extra);
0d39fa9c
LP
1248
1249 t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1250 if (!t)
1251 return -ENOMEM;
1252
1253 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1254
858d36c1 1255 *ret = path_simplify(t, false);
0d39fa9c
LP
1256 return 0;
1257}
1258
1259int tempfn_random(const char *p, const char *extra, char **ret) {
1260 const char *fn;
1261 char *t, *x;
1262 uint64_t u;
1263 unsigned i;
1264
0d39fa9c
LP
1265 assert(ret);
1266
09942654
LP
1267 if (isempty(p))
1268 return -EINVAL;
1269 if (path_equal(p, "/"))
1270 return -EINVAL;
1271
0d39fa9c
LP
1272 /*
1273 * Turns this:
1274 * /foo/bar/waldo
1275 *
1276 * Into this:
1277 * /foo/bar/.#<extra>waldobaa2a261115984a9
1278 */
1279
1280 fn = basename(p);
1281 if (!filename_is_valid(fn))
1282 return -EINVAL;
1283
ad5d4b17 1284 extra = strempty(extra);
0d39fa9c
LP
1285
1286 t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1287 if (!t)
1288 return -ENOMEM;
1289
1290 x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1291
1292 u = random_u64();
1293 for (i = 0; i < 16; i++) {
1294 *(x++) = hexchar(u & 0xF);
1295 u >>= 4;
1296 }
1297
1298 *x = 0;
1299
858d36c1 1300 *ret = path_simplify(t, false);
0d39fa9c
LP
1301 return 0;
1302}
1303
1304int tempfn_random_child(const char *p, const char *extra, char **ret) {
1305 char *t, *x;
1306 uint64_t u;
1307 unsigned i;
992e8f22 1308 int r;
0d39fa9c 1309
0d39fa9c
LP
1310 assert(ret);
1311
1312 /* Turns this:
1313 * /foo/bar/waldo
1314 * Into this:
1315 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1316 */
1317
992e8f22
LP
1318 if (!p) {
1319 r = tmp_dir(&p);
1320 if (r < 0)
1321 return r;
43231f00 1322 }
992e8f22 1323
ad5d4b17 1324 extra = strempty(extra);
0d39fa9c
LP
1325
1326 t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1327 if (!t)
1328 return -ENOMEM;
1329
43231f00
FB
1330 if (isempty(p))
1331 x = stpcpy(stpcpy(t, ".#"), extra);
1332 else
1333 x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
0d39fa9c
LP
1334
1335 u = random_u64();
1336 for (i = 0; i < 16; i++) {
1337 *(x++) = hexchar(u & 0xF);
1338 u >>= 4;
1339 }
1340
1341 *x = 0;
1342
858d36c1 1343 *ret = path_simplify(t, false);
0d39fa9c
LP
1344 return 0;
1345}
33d52ab9
LP
1346
1347int write_timestamp_file_atomic(const char *fn, usec_t n) {
1348 char ln[DECIMAL_STR_MAX(n)+2];
1349
1350 /* Creates a "timestamp" file, that contains nothing but a
1351 * usec_t timestamp, formatted in ASCII. */
1352
1353 if (n <= 0 || n >= USEC_INFINITY)
1354 return -ERANGE;
1355
1356 xsprintf(ln, USEC_FMT "\n", n);
1357
1358 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1359}
1360
1361int read_timestamp_file(const char *fn, usec_t *ret) {
1362 _cleanup_free_ char *ln = NULL;
1363 uint64_t t;
1364 int r;
1365
1366 r = read_one_line_file(fn, &ln);
1367 if (r < 0)
1368 return r;
1369
1370 r = safe_atou64(ln, &t);
1371 if (r < 0)
1372 return r;
1373
1374 if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1375 return -ERANGE;
1376
1377 *ret = (usec_t) t;
1378 return 0;
1379}
d390f8ef
LP
1380
1381int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1382 int r;
1383
1384 assert(s);
1385
1386 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1387 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1388 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1389 * element, but not before the first one. */
1390
1391 if (!f)
1392 f = stdout;
1393
1394 if (space) {
1395 if (!separator)
1396 separator = " ";
1397
1398 if (*space) {
1399 r = fputs(separator, f);
1400 if (r < 0)
1401 return r;
1402 }
1403
1404 *space = true;
1405 }
1406
1407 return fputs(s, f);
1408}
03532f0a
LP
1409
1410int open_tmpfile_unlinkable(const char *directory, int flags) {
1411 char *p;
992e8f22 1412 int fd, r;
03532f0a 1413
992e8f22
LP
1414 if (!directory) {
1415 r = tmp_dir(&directory);
1416 if (r < 0)
1417 return r;
09942654
LP
1418 } else if (isempty(directory))
1419 return -EINVAL;
03532f0a
LP
1420
1421 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1422
03532f0a
LP
1423 /* Try O_TMPFILE first, if it is supported */
1424 fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1425 if (fd >= 0)
1426 return fd;
03532f0a
LP
1427
1428 /* Fall back to unguessable name + unlinking */
1429 p = strjoina(directory, "/systemd-tmp-XXXXXX");
1430
646853bd 1431 fd = mkostemp_safe(p);
03532f0a
LP
1432 if (fd < 0)
1433 return fd;
1434
1435 (void) unlink(p);
1436
1437 return fd;
1438}
1439
1440int open_tmpfile_linkable(const char *target, int flags, char **ret_path) {
1441 _cleanup_free_ char *tmp = NULL;
1442 int r, fd;
1443
1444 assert(target);
1445 assert(ret_path);
1446
1447 /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1448 assert((flags & O_EXCL) == 0);
1449
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. */
1453
0c462ea4
LP
1454 fd = open_parent(target, O_TMPFILE|flags, 0640);
1455 if (fd >= 0) {
1456 *ret_path = NULL;
1457 return fd;
03532f0a 1458 }
03532f0a 1459
0c462ea4
LP
1460 log_debug_errno(fd, "Failed to use O_TMPFILE for %s: %m", target);
1461
03532f0a
LP
1462 r = tempfn_random(target, NULL, &tmp);
1463 if (r < 0)
1464 return r;
1465
1466 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640);
1467 if (fd < 0)
1468 return -errno;
1469
ae2a15bc 1470 *ret_path = TAKE_PTR(tmp);
03532f0a
LP
1471
1472 return fd;
1473}
1474
504afd7c
ZJS
1475int open_serialization_fd(const char *ident) {
1476 int fd = -1;
1477
1478 fd = memfd_create(ident, MFD_CLOEXEC);
1479 if (fd < 0) {
1480 const char *path;
1481
df0ff127 1482 path = getpid_cached() == 1 ? "/run/systemd" : "/tmp";
504afd7c
ZJS
1483 fd = open_tmpfile_unlinkable(path, O_RDWR|O_CLOEXEC);
1484 if (fd < 0)
1485 return fd;
1486
1487 log_debug("Serializing %s to %s.", ident, path);
1488 } else
1489 log_debug("Serializing %s to memfd.", ident);
1490
1491 return fd;
1492}
1493
03532f0a
LP
1494int link_tmpfile(int fd, const char *path, const char *target) {
1495
1496 assert(fd >= 0);
1497 assert(target);
1498
1499 /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1500 * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1501 * on the directory, and renameat2() is used instead.
1502 *
f8e2f4d6 1503 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
03532f0a
LP
1504 * operation currently (renameat2() does), and there is no nice way to emulate this. */
1505
1506 if (path) {
1507 if (rename_noreplace(AT_FDCWD, path, AT_FDCWD, target) < 0)
1508 return -errno;
1509 } else {
fbd0b64f 1510 char proc_fd_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
03532f0a
LP
1511
1512 xsprintf(proc_fd_path, "/proc/self/fd/%i", fd);
1513
1514 if (linkat(AT_FDCWD, proc_fd_path, AT_FDCWD, target, AT_SYMLINK_FOLLOW) < 0)
1515 return -errno;
1516 }
1517
1518 return 0;
1519}
03c2b288
LP
1520
1521int read_nul_string(FILE *f, char **ret) {
1522 _cleanup_free_ char *x = NULL;
1523 size_t allocated = 0, n = 0;
1524
1525 assert(f);
1526 assert(ret);
1527
1528 /* Reads a NUL-terminated string from the specified file. */
1529
1530 for (;;) {
1531 int c;
1532
1533 if (!GREEDY_REALLOC(x, allocated, n+2))
1534 return -ENOMEM;
1535
1536 c = fgetc(f);
1537 if (c == 0) /* Terminate at NUL byte */
1538 break;
1539 if (c == EOF) {
1540 if (ferror(f))
1541 return -errno;
1542 break; /* Terminate at EOF */
1543 }
1544
1545 x[n++] = (char) c;
1546 }
1547
1548 if (x)
1549 x[n] = 0;
1550 else {
1551 x = new0(char, 1);
1552 if (!x)
1553 return -ENOMEM;
1554 }
1555
ae2a15bc 1556 *ret = TAKE_PTR(x);
03c2b288
LP
1557
1558 return 0;
1559}
676bcb0f
LP
1560
1561int mkdtemp_malloc(const char *template, char **ret) {
3f403039
LP
1562 _cleanup_free_ char *p = NULL;
1563 int r;
676bcb0f 1564
676bcb0f
LP
1565 assert(ret);
1566
3f403039
LP
1567 if (template)
1568 p = strdup(template);
1569 else {
1570 const char *tmp;
1571
1572 r = tmp_dir(&tmp);
1573 if (r < 0)
1574 return r;
1575
1576 p = strjoin(tmp, "/XXXXXX");
1577 }
676bcb0f
LP
1578 if (!p)
1579 return -ENOMEM;
1580
3f403039 1581 if (!mkdtemp(p))
676bcb0f 1582 return -errno;
676bcb0f 1583
3f403039 1584 *ret = TAKE_PTR(p);
676bcb0f
LP
1585 return 0;
1586}
4f9a66a3 1587
57d6f700 1588DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile);
f858e514 1589
4f9a66a3
LP
1590int read_line(FILE *f, size_t limit, char **ret) {
1591 _cleanup_free_ char *buffer = NULL;
1592 size_t n = 0, allocated = 0, count = 0;
4f9a66a3
LP
1593
1594 assert(f);
1595
1596 /* Something like a bounded version of getline().
1597 *
1598 * Considers EOF, \n and \0 end of line delimiters, and does not include these delimiters in the string
1599 * returned.
1600 *
1601 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1602 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1603 *
1604 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1605 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1606 *
1607 * If a line shall be skipped ret may be initialized as NULL. */
1608
1609 if (ret) {
1610 if (!GREEDY_REALLOC(buffer, allocated, 1))
1611 return -ENOMEM;
1612 }
1613
f858e514 1614 {
3f691417 1615 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
f858e514 1616 flockfile(f);
4f9a66a3 1617
f858e514
ZJS
1618 for (;;) {
1619 int c;
4f9a66a3 1620
f858e514
ZJS
1621 if (n >= limit)
1622 return -ENOBUFS;
4f9a66a3 1623
f858e514
ZJS
1624 errno = 0;
1625 c = fgetc_unlocked(f);
1626 if (c == EOF) {
1627 /* if we read an error, and have no data to return, then propagate the error */
1628 if (ferror_unlocked(f) && n == 0)
1629 return errno > 0 ? -errno : -EIO;
1630
1631 break;
4f9a66a3
LP
1632 }
1633
f858e514 1634 count++;
4f9a66a3 1635
f858e514
ZJS
1636 if (IN_SET(c, '\n', 0)) /* Reached a delimiter */
1637 break;
4f9a66a3 1638
f858e514
ZJS
1639 if (ret) {
1640 if (!GREEDY_REALLOC(buffer, allocated, n + 2))
1641 return -ENOMEM;
4f9a66a3 1642
f858e514 1643 buffer[n] = (char) c;
4f9a66a3
LP
1644 }
1645
f858e514 1646 n++;
4f9a66a3 1647 }
4f9a66a3
LP
1648 }
1649
4f9a66a3
LP
1650 if (ret) {
1651 buffer[n] = 0;
1652
1cc6c93a 1653 *ret = TAKE_PTR(buffer);
4f9a66a3
LP
1654 }
1655
1656 return (int) count;
1657}