]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/fileio.c
tree-wide: make ++/-- usage consistent WRT spacing
[thirdparty/systemd.git] / src / basic / fileio.c
CommitLineData
a5c32cff
HH
1/***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18***/
19
11c3a366
TA
20#include <errno.h>
21#include <fcntl.h>
22#include <limits.h>
23#include <stdarg.h>
24#include <stdint.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/stat.h>
28#include <sys/types.h>
a5c32cff 29#include <unistd.h>
cda134ab 30
b5efdb8a 31#include "alloc-util.h"
4f5dd394
LP
32#include "ctype.h"
33#include "escape.h"
3ffd4af2
LP
34#include "fd-util.h"
35#include "fileio.h"
f4f15635 36#include "fs-util.h"
0d39fa9c 37#include "hexdecoct.h"
93cc7779
TA
38#include "log.h"
39#include "macro.h"
33d52ab9 40#include "parse-util.h"
0d39fa9c
LP
41#include "path-util.h"
42#include "random-util.h"
33d52ab9 43#include "stdio-util.h"
07630cea 44#include "string-util.h"
a5c32cff 45#include "strv.h"
93cc7779 46#include "time-util.h"
affb60b1 47#include "umask-util.h"
335c46b5 48#include "utf8.h"
a5c32cff 49
40beecdb 50int write_string_stream(FILE *f, const char *line, bool enforce_newline) {
dacd6cee 51
717603e3
LP
52 assert(f);
53 assert(line);
54
fec6fc6b 55 fputs(line, f);
40beecdb 56 if (enforce_newline && !endswith(line, "\n"))
a5c32cff
HH
57 fputc('\n', f);
58
dacd6cee 59 return fflush_and_check(f);
a5c32cff
HH
60}
61
4c1fc3e4 62static int write_string_file_atomic(const char *fn, const char *line, bool enforce_newline) {
a5c32cff
HH
63 _cleanup_fclose_ FILE *f = NULL;
64 _cleanup_free_ char *p = NULL;
65 int r;
66
67 assert(fn);
68 assert(line);
69
70 r = fopen_temporary(fn, &f, &p);
71 if (r < 0)
72 return r;
73
0d39fa9c 74 (void) fchmod_umask(fileno(f), 0644);
a5c32cff 75
4c1fc3e4 76 r = write_string_stream(f, line, enforce_newline);
f2997962 77 if (r >= 0) {
a5c32cff
HH
78 if (rename(p, fn) < 0)
79 r = -errno;
a5c32cff
HH
80 }
81
a5c32cff 82 if (r < 0)
0d39fa9c 83 (void) unlink(p);
a5c32cff
HH
84
85 return r;
86}
87
4c1fc3e4
DM
88int write_string_file(const char *fn, const char *line, WriteStringFileFlags flags) {
89 _cleanup_fclose_ FILE *f = NULL;
eb3da901 90 int q, r;
4c1fc3e4
DM
91
92 assert(fn);
93 assert(line);
94
95 if (flags & WRITE_STRING_FILE_ATOMIC) {
96 assert(flags & WRITE_STRING_FILE_CREATE);
97
eb3da901
LP
98 r = write_string_file_atomic(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
99 if (r < 0)
100 goto fail;
101
102 return r;
4c1fc3e4
DM
103 }
104
105 if (flags & WRITE_STRING_FILE_CREATE) {
106 f = fopen(fn, "we");
eb3da901
LP
107 if (!f) {
108 r = -errno;
109 goto fail;
110 }
4c1fc3e4
DM
111 } else {
112 int fd;
113
114 /* We manually build our own version of fopen(..., "we") that
115 * works without O_CREAT */
116 fd = open(fn, O_WRONLY|O_CLOEXEC|O_NOCTTY);
eb3da901
LP
117 if (fd < 0) {
118 r = -errno;
119 goto fail;
120 }
4c1fc3e4
DM
121
122 f = fdopen(fd, "we");
123 if (!f) {
eb3da901 124 r = -errno;
4c1fc3e4 125 safe_close(fd);
eb3da901 126 goto fail;
4c1fc3e4
DM
127 }
128 }
129
eb3da901
LP
130 r = write_string_stream(f, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
131 if (r < 0)
132 goto fail;
133
134 return 0;
135
136fail:
137 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
138 return r;
139
140 f = safe_fclose(f);
141
142 /* OK, the operation failed, but let's see if the right
143 * contents in place already. If so, eat up the error. */
144
145 q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
146 if (q <= 0)
147 return r;
148
149 return 0;
4c1fc3e4
DM
150}
151
a5c32cff
HH
152int read_one_line_file(const char *fn, char **line) {
153 _cleanup_fclose_ FILE *f = NULL;
154 char t[LINE_MAX], *c;
155
156 assert(fn);
157 assert(line);
158
159 f = fopen(fn, "re");
160 if (!f)
161 return -errno;
162
163 if (!fgets(t, sizeof(t), f)) {
164
165 if (ferror(f))
f5e5c28f 166 return errno > 0 ? -errno : -EIO;
a5c32cff
HH
167
168 t[0] = 0;
169 }
170
171 c = strdup(t);
172 if (!c)
173 return -ENOMEM;
174 truncate_nl(c);
175
176 *line = c;
177 return 0;
178}
179
eb3da901
LP
180int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
181 _cleanup_fclose_ FILE *f = NULL;
182 _cleanup_free_ char *buf = NULL;
183 size_t l, k;
15dee3f0 184
eb3da901
LP
185 assert(fn);
186 assert(blob);
187
188 l = strlen(blob);
189
190 if (accept_extra_nl && endswith(blob, "\n"))
191 accept_extra_nl = false;
192
193 buf = malloc(l + accept_extra_nl + 1);
194 if (!buf)
195 return -ENOMEM;
196
197 f = fopen(fn, "re");
198 if (!f)
199 return -errno;
200
201 /* We try to read one byte more than we need, so that we know whether we hit eof */
202 errno = 0;
203 k = fread(buf, 1, l + accept_extra_nl + 1, f);
204 if (ferror(f))
205 return errno > 0 ? -errno : -EIO;
206
207 if (k != l && k != l + accept_extra_nl)
208 return 0;
209 if (memcmp(buf, blob, l) != 0)
210 return 0;
211 if (k > l && buf[l] != '\n')
212 return 0;
15dee3f0 213
eb3da901 214 return 1;
15dee3f0
LP
215}
216
717603e3 217int read_full_stream(FILE *f, char **contents, size_t *size) {
a5c32cff
HH
218 size_t n, l;
219 _cleanup_free_ char *buf = NULL;
220 struct stat st;
221
717603e3 222 assert(f);
a5c32cff
HH
223 assert(contents);
224
a5c32cff
HH
225 if (fstat(fileno(f), &st) < 0)
226 return -errno;
227
717603e3 228 n = LINE_MAX;
a5c32cff 229
717603e3
LP
230 if (S_ISREG(st.st_mode)) {
231
232 /* Safety check */
233 if (st.st_size > 4*1024*1024)
234 return -E2BIG;
235
236 /* Start with the right file size, but be prepared for
237 * files from /proc which generally report a file size
238 * of 0 */
239 if (st.st_size > 0)
240 n = st.st_size;
241 }
a5c32cff 242
717603e3 243 l = 0;
a5c32cff
HH
244 for (;;) {
245 char *t;
246 size_t k;
247
248 t = realloc(buf, n+1);
249 if (!t)
250 return -ENOMEM;
251
252 buf = t;
253 k = fread(buf + l, 1, n - l, f);
254
255 if (k <= 0) {
256 if (ferror(f))
257 return -errno;
258
259 break;
260 }
261
262 l += k;
263 n *= 2;
264
265 /* Safety check */
266 if (n > 4*1024*1024)
267 return -E2BIG;
268 }
269
270 buf[l] = 0;
271 *contents = buf;
d78a28e3 272 buf = NULL; /* do not free */
a5c32cff
HH
273
274 if (size)
275 *size = l;
276
277 return 0;
278}
279
717603e3
LP
280int read_full_file(const char *fn, char **contents, size_t *size) {
281 _cleanup_fclose_ FILE *f = NULL;
282
283 assert(fn);
284 assert(contents);
285
286 f = fopen(fn, "re");
287 if (!f)
288 return -errno;
289
290 return read_full_stream(f, contents, size);
291}
292
f73141d7 293static int parse_env_file_internal(
717603e3 294 FILE *f,
a5c32cff 295 const char *fname,
f73141d7 296 const char *newline,
335c46b5 297 int (*push) (const char *filename, unsigned line,
a5f6c30d
MS
298 const char *key, char *value, void *userdata, int *n_pushed),
299 void *userdata,
300 int *n_pushed) {
f73141d7
LP
301
302 _cleanup_free_ char *contents = NULL, *key = NULL;
2b77f67e 303 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;
f73141d7
LP
304 char *p, *value = NULL;
305 int r;
335c46b5 306 unsigned line = 1;
a5c32cff 307
f73141d7
LP
308 enum {
309 PRE_KEY,
310 KEY,
f73141d7
LP
311 PRE_VALUE,
312 VALUE,
313 VALUE_ESCAPE,
314 SINGLE_QUOTE_VALUE,
315 SINGLE_QUOTE_VALUE_ESCAPE,
316 DOUBLE_QUOTE_VALUE,
317 DOUBLE_QUOTE_VALUE_ESCAPE,
318 COMMENT,
319 COMMENT_ESCAPE
320 } state = PRE_KEY;
a5c32cff 321
f73141d7 322 assert(newline);
a5c32cff 323
717603e3
LP
324 if (f)
325 r = read_full_stream(f, &contents, NULL);
326 else
327 r = read_full_file(fname, &contents, NULL);
1c17cbed 328 if (r < 0)
a5c32cff
HH
329 return r;
330
f73141d7
LP
331 for (p = contents; *p; p++) {
332 char c = *p;
333
334 switch (state) {
335
336 case PRE_KEY:
ebc05a09 337 if (strchr(COMMENTS, c))
f73141d7
LP
338 state = COMMENT;
339 else if (!strchr(WHITESPACE, c)) {
340 state = KEY;
2b77f67e
LP
341 last_key_whitespace = (size_t) -1;
342
ca2d3784 343 if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) {
f73141d7
LP
344 r = -ENOMEM;
345 goto fail;
346 }
347
348 key[n_key++] = c;
349 }
350 break;
351
352 case KEY:
353 if (strchr(newline, c)) {
354 state = PRE_KEY;
313cefa1 355 line++;
f73141d7 356 n_key = 0;
2b77f67e 357 } else if (c == '=') {
f73141d7 358 state = PRE_VALUE;
2b77f67e
LP
359 last_value_whitespace = (size_t) -1;
360 } else {
361 if (!strchr(WHITESPACE, c))
362 last_key_whitespace = (size_t) -1;
363 else if (last_key_whitespace == (size_t) -1)
364 last_key_whitespace = n_key;
365
ca2d3784 366 if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) {
f73141d7
LP
367 r = -ENOMEM;
368 goto fail;
369 }
370
371 key[n_key++] = c;
372 }
a5c32cff 373
f73141d7
LP
374 break;
375
f73141d7 376 case PRE_VALUE:
98f59e59 377 if (strchr(newline, c)) {
f73141d7 378 state = PRE_KEY;
313cefa1 379 line++;
f73141d7 380 key[n_key] = 0;
a5c32cff 381
f73141d7
LP
382 if (value)
383 value[n_value] = 0;
a5c32cff 384
ebc05a09 385 /* strip trailing whitespace from key */
2b77f67e
LP
386 if (last_key_whitespace != (size_t) -1)
387 key[last_key_whitespace] = 0;
ebc05a09 388
a5f6c30d 389 r = push(fname, line, key, value, userdata, n_pushed);
f73141d7
LP
390 if (r < 0)
391 goto fail;
392
393 n_key = 0;
394 value = NULL;
395 value_alloc = n_value = 0;
2b77f67e 396
f73141d7
LP
397 } else if (c == '\'')
398 state = SINGLE_QUOTE_VALUE;
399 else if (c == '\"')
400 state = DOUBLE_QUOTE_VALUE;
401 else if (c == '\\')
402 state = VALUE_ESCAPE;
403 else if (!strchr(WHITESPACE, c)) {
404 state = VALUE;
405
ca2d3784 406 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
f73141d7
LP
407 r = -ENOMEM;
408 goto fail;
409 }
410
411 value[n_value++] = c;
412 }
413
414 break;
415
416 case VALUE:
417 if (strchr(newline, c)) {
418 state = PRE_KEY;
313cefa1 419 line++;
98f59e59 420
f73141d7
LP
421 key[n_key] = 0;
422
423 if (value)
424 value[n_value] = 0;
425
2b77f67e
LP
426 /* Chomp off trailing whitespace from value */
427 if (last_value_whitespace != (size_t) -1)
428 value[last_value_whitespace] = 0;
f73141d7 429
ebc05a09 430 /* strip trailing whitespace from key */
2b77f67e
LP
431 if (last_key_whitespace != (size_t) -1)
432 key[last_key_whitespace] = 0;
ebc05a09 433
a5f6c30d 434 r = push(fname, line, key, value, userdata, n_pushed);
f73141d7
LP
435 if (r < 0)
436 goto fail;
437
438 n_key = 0;
439 value = NULL;
440 value_alloc = n_value = 0;
2b77f67e 441
f73141d7
LP
442 } else if (c == '\\') {
443 state = VALUE_ESCAPE;
2b77f67e 444 last_value_whitespace = (size_t) -1;
f73141d7
LP
445 } else {
446 if (!strchr(WHITESPACE, c))
2b77f67e
LP
447 last_value_whitespace = (size_t) -1;
448 else if (last_value_whitespace == (size_t) -1)
449 last_value_whitespace = n_value;
f73141d7 450
ca2d3784 451 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
f73141d7
LP
452 r = -ENOMEM;
453 goto fail;
454 }
455
456 value[n_value++] = c;
457 }
458
459 break;
460
461 case VALUE_ESCAPE:
462 state = VALUE;
463
464 if (!strchr(newline, c)) {
465 /* Escaped newlines we eat up entirely */
ca2d3784 466 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
f73141d7
LP
467 r = -ENOMEM;
468 goto fail;
469 }
470
471 value[n_value++] = c;
472 }
473 break;
474
475 case SINGLE_QUOTE_VALUE:
476 if (c == '\'')
477 state = PRE_VALUE;
478 else if (c == '\\')
479 state = SINGLE_QUOTE_VALUE_ESCAPE;
480 else {
ca2d3784 481 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
f73141d7
LP
482 r = -ENOMEM;
483 goto fail;
484 }
a5c32cff 485
f73141d7
LP
486 value[n_value++] = c;
487 }
a5c32cff 488
f73141d7 489 break;
a5c32cff 490
f73141d7
LP
491 case SINGLE_QUOTE_VALUE_ESCAPE:
492 state = SINGLE_QUOTE_VALUE;
a5c32cff 493
f73141d7 494 if (!strchr(newline, c)) {
ca2d3784 495 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
a5c32cff 496 r = -ENOMEM;
a5c32cff
HH
497 goto fail;
498 }
499
f73141d7
LP
500 value[n_value++] = c;
501 }
502 break;
503
504 case DOUBLE_QUOTE_VALUE:
505 if (c == '\"')
506 state = PRE_VALUE;
507 else if (c == '\\')
508 state = DOUBLE_QUOTE_VALUE_ESCAPE;
509 else {
ca2d3784 510 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
f73141d7
LP
511 r = -ENOMEM;
512 goto fail;
a5c32cff
HH
513 }
514
f73141d7
LP
515 value[n_value++] = c;
516 }
517
518 break;
519
520 case DOUBLE_QUOTE_VALUE_ESCAPE:
521 state = DOUBLE_QUOTE_VALUE;
a5c32cff 522
f73141d7 523 if (!strchr(newline, c)) {
ca2d3784 524 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
f73141d7
LP
525 r = -ENOMEM;
526 goto fail;
527 }
a5c32cff 528
f73141d7 529 value[n_value++] = c;
a5c32cff 530 }
f73141d7
LP
531 break;
532
533 case COMMENT:
534 if (c == '\\')
535 state = COMMENT_ESCAPE;
335c46b5 536 else if (strchr(newline, c)) {
f73141d7 537 state = PRE_KEY;
313cefa1 538 line++;
335c46b5 539 }
f73141d7
LP
540 break;
541
542 case COMMENT_ESCAPE:
543 state = COMMENT;
544 break;
a5c32cff 545 }
f73141d7
LP
546 }
547
548 if (state == PRE_VALUE ||
549 state == VALUE ||
550 state == VALUE_ESCAPE ||
551 state == SINGLE_QUOTE_VALUE ||
552 state == SINGLE_QUOTE_VALUE_ESCAPE ||
553 state == DOUBLE_QUOTE_VALUE ||
554 state == DOUBLE_QUOTE_VALUE_ESCAPE) {
a5c32cff 555
f73141d7
LP
556 key[n_key] = 0;
557
558 if (value)
559 value[n_value] = 0;
560
2b77f67e
LP
561 if (state == VALUE)
562 if (last_value_whitespace != (size_t) -1)
563 value[last_value_whitespace] = 0;
564
ebc05a09 565 /* strip trailing whitespace from key */
2b77f67e
LP
566 if (last_key_whitespace != (size_t) -1)
567 key[last_key_whitespace] = 0;
ebc05a09 568
a5f6c30d 569 r = push(fname, line, key, value, userdata, n_pushed);
f73141d7
LP
570 if (r < 0)
571 goto fail;
a5c32cff
HH
572 }
573
f73141d7
LP
574 return 0;
575
a5c32cff 576fail:
f73141d7 577 free(value);
a5c32cff
HH
578 return r;
579}
580
717603e3
LP
581static int parse_env_file_push(
582 const char *filename, unsigned line,
583 const char *key, char *value,
a5f6c30d
MS
584 void *userdata,
585 int *n_pushed) {
335c46b5 586
f27f0e21
GB
587 const char *k;
588 va_list aq, *ap = userdata;
589
590 if (!utf8_is_valid(key)) {
717603e3 591 _cleanup_free_ char *p;
550a40ec 592
717603e3
LP
593 p = utf8_escape_invalid(key);
594 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p);
f27f0e21
GB
595 return -EINVAL;
596 }
597
598 if (value && !utf8_is_valid(value)) {
717603e3 599 _cleanup_free_ char *p;
550a40ec 600
717603e3
LP
601 p = utf8_escape_invalid(value);
602 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, p);
f27f0e21
GB
603 return -EINVAL;
604 }
a5c32cff 605
f27f0e21 606 va_copy(aq, *ap);
a5c32cff 607
f27f0e21
GB
608 while ((k = va_arg(aq, const char *))) {
609 char **v;
a5c32cff 610
f27f0e21 611 v = va_arg(aq, char **);
a5c32cff 612
f27f0e21
GB
613 if (streq(key, k)) {
614 va_end(aq);
615 free(*v);
616 *v = value;
a5f6c30d
MS
617
618 if (n_pushed)
619 (*n_pushed)++;
620
f27f0e21 621 return 1;
f73141d7 622 }
335c46b5 623 }
a5c32cff 624
f27f0e21 625 va_end(aq);
f73141d7 626 free(value);
717603e3 627
f73141d7
LP
628 return 0;
629}
a5c32cff 630
f73141d7
LP
631int parse_env_file(
632 const char *fname,
633 const char *newline, ...) {
a5c32cff 634
f73141d7 635 va_list ap;
a5f6c30d 636 int r, n_pushed = 0;
a5c32cff 637
f73141d7
LP
638 if (!newline)
639 newline = NEWLINE;
a5c32cff 640
f73141d7 641 va_start(ap, newline);
a5f6c30d 642 r = parse_env_file_internal(NULL, fname, newline, parse_env_file_push, &ap, &n_pushed);
f73141d7 643 va_end(ap);
a5c32cff 644
a5f6c30d 645 return r < 0 ? r : n_pushed;
f73141d7 646}
a5c32cff 647
717603e3
LP
648static int load_env_file_push(
649 const char *filename, unsigned line,
650 const char *key, char *value,
a5f6c30d
MS
651 void *userdata,
652 int *n_pushed) {
f27f0e21
GB
653 char ***m = userdata;
654 char *p;
655 int r;
a5c32cff 656
f27f0e21 657 if (!utf8_is_valid(key)) {
b5d74213
ZJS
658 _cleanup_free_ char *t = utf8_escape_invalid(key);
659
717603e3 660 log_error("%s:%u: invalid UTF-8 for key '%s', ignoring.", strna(filename), line, t);
f27f0e21
GB
661 return -EINVAL;
662 }
663
664 if (value && !utf8_is_valid(value)) {
b5d74213
ZJS
665 _cleanup_free_ char *t = utf8_escape_invalid(value);
666
717603e3 667 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, t);
f27f0e21
GB
668 return -EINVAL;
669 }
a5c32cff 670
f27f0e21
GB
671 p = strjoin(key, "=", strempty(value), NULL);
672 if (!p)
673 return -ENOMEM;
335c46b5 674
6e18964d
ZJS
675 r = strv_consume(m, p);
676 if (r < 0)
f27f0e21 677 return r;
a5c32cff 678
a5f6c30d
MS
679 if (n_pushed)
680 (*n_pushed)++;
681
f73141d7
LP
682 free(value);
683 return 0;
684}
685
717603e3
LP
686int load_env_file(FILE *f, const char *fname, const char *newline, char ***rl) {
687 char **m = NULL;
688 int r;
689
690 if (!newline)
691 newline = NEWLINE;
692
a5f6c30d 693 r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
717603e3
LP
694 if (r < 0) {
695 strv_free(m);
696 return r;
697 }
698
699 *rl = m;
700 return 0;
701}
702
703static int load_env_file_push_pairs(
704 const char *filename, unsigned line,
705 const char *key, char *value,
a5f6c30d
MS
706 void *userdata,
707 int *n_pushed) {
717603e3
LP
708 char ***m = userdata;
709 int r;
710
711 if (!utf8_is_valid(key)) {
712 _cleanup_free_ char *t = utf8_escape_invalid(key);
713
714 log_error("%s:%u: invalid UTF-8 for key '%s', ignoring.", strna(filename), line, t);
715 return -EINVAL;
716 }
717
718 if (value && !utf8_is_valid(value)) {
719 _cleanup_free_ char *t = utf8_escape_invalid(value);
720
721 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, t);
722 return -EINVAL;
723 }
724
725 r = strv_extend(m, key);
726 if (r < 0)
727 return -ENOMEM;
728
729 if (!value) {
730 r = strv_extend(m, "");
731 if (r < 0)
732 return -ENOMEM;
733 } else {
734 r = strv_push(m, value);
735 if (r < 0)
736 return r;
737 }
738
a5f6c30d
MS
739 if (n_pushed)
740 (*n_pushed)++;
741
717603e3
LP
742 return 0;
743}
744
745int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
f73141d7
LP
746 char **m = NULL;
747 int r;
a5c32cff 748
f73141d7
LP
749 if (!newline)
750 newline = NEWLINE;
751
a5f6c30d 752 r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
f73141d7
LP
753 if (r < 0) {
754 strv_free(m);
755 return r;
a5c32cff
HH
756 }
757
758 *rl = m;
a5c32cff
HH
759 return 0;
760}
761
768100ef
LP
762static void write_env_var(FILE *f, const char *v) {
763 const char *p;
764
765 p = strchr(v, '=');
766 if (!p) {
767 /* Fallback */
768 fputs(v, f);
769 fputc('\n', f);
770 return;
771 }
772
773 p++;
774 fwrite(v, 1, p-v, f);
775
0ce5a806 776 if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
768100ef
LP
777 fputc('\"', f);
778
779 for (; *p; p++) {
0ce5a806 780 if (strchr(SHELL_NEED_ESCAPE, *p))
768100ef
LP
781 fputc('\\', f);
782
783 fputc(*p, f);
784 }
785
786 fputc('\"', f);
787 } else
788 fputs(p, f);
789
790 fputc('\n', f);
791}
792
a5c32cff 793int write_env_file(const char *fname, char **l) {
7fd1b19b 794 _cleanup_fclose_ FILE *f = NULL;
736937e5
LP
795 _cleanup_free_ char *p = NULL;
796 char **i;
a5c32cff
HH
797 int r;
798
736937e5
LP
799 assert(fname);
800
a5c32cff
HH
801 r = fopen_temporary(fname, &f, &p);
802 if (r < 0)
803 return r;
804
805 fchmod_umask(fileno(f), 0644);
806
768100ef
LP
807 STRV_FOREACH(i, l)
808 write_env_var(f, *i);
a5c32cff 809
736937e5
LP
810 r = fflush_and_check(f);
811 if (r >= 0) {
812 if (rename(p, fname) >= 0)
813 return 0;
a5c32cff 814
736937e5 815 r = -errno;
a5c32cff
HH
816 }
817
736937e5 818 unlink(p);
a5c32cff
HH
819 return r;
820}
68fee104
ZJS
821
822int executable_is_script(const char *path, char **interpreter) {
823 int r;
c8b32e11 824 _cleanup_free_ char *line = NULL;
68fee104
ZJS
825 int len;
826 char *ans;
827
828 assert(path);
829
830 r = read_one_line_file(path, &line);
831 if (r < 0)
832 return r;
833
834 if (!startswith(line, "#!"))
835 return 0;
836
837 ans = strstrip(line + 2);
838 len = strcspn(ans, " \t");
839
840 if (len == 0)
841 return 0;
842
843 ans = strndup(ans, len);
844 if (!ans)
845 return -ENOMEM;
846
847 *interpreter = ans;
848 return 1;
849}
69ab8088
ZJS
850
851/**
0a7b53bd 852 * Retrieve one field from a file like /proc/self/status. pattern
c4cd1d4d
AK
853 * should not include whitespace or the delimiter (':'). pattern matches only
854 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
855 * zeros after the ':' will be skipped. field must be freed afterwards.
856 * terminator specifies the terminating characters of the field value (not
857 * included in the value).
69ab8088 858 */
c4cd1d4d 859int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
69ab8088 860 _cleanup_free_ char *status = NULL;
90110825 861 char *t, *f;
69ab8088
ZJS
862 size_t len;
863 int r;
864
c4cd1d4d 865 assert(terminator);
69ab8088 866 assert(filename);
7ff7394d 867 assert(pattern);
69ab8088
ZJS
868 assert(field);
869
870 r = read_full_file(filename, &status, NULL);
871 if (r < 0)
872 return r;
873
c4cd1d4d
AK
874 t = status;
875
876 do {
877 bool pattern_ok;
878
879 do {
880 t = strstr(t, pattern);
881 if (!t)
882 return -ENOENT;
883
884 /* Check that pattern occurs in beginning of line. */
885 pattern_ok = (t == status || t[-1] == '\n');
886
887 t += strlen(pattern);
888
889 } while (!pattern_ok);
890
891 t += strspn(t, " \t");
892 if (!*t)
893 return -ENOENT;
894
895 } while (*t != ':');
896
897 t++;
69ab8088 898
4ec29144 899 if (*t) {
1e5413f7
ZJS
900 t += strspn(t, " \t");
901
902 /* Also skip zeros, because when this is used for
903 * capabilities, we don't want the zeros. This way the
904 * same capability set always maps to the same string,
905 * irrespective of the total capability set size. For
906 * other numbers it shouldn't matter. */
907 t += strspn(t, "0");
4ec29144
ZJS
908 /* Back off one char if there's nothing but whitespace
909 and zeros */
1e5413f7 910 if (!*t || isspace(*t))
313cefa1 911 t--;
4ec29144 912 }
69ab8088 913
c4cd1d4d 914 len = strcspn(t, terminator);
69ab8088 915
90110825
LP
916 f = strndup(t, len);
917 if (!f)
69ab8088
ZJS
918 return -ENOMEM;
919
90110825 920 *field = f;
69ab8088
ZJS
921 return 0;
922}
0d39fa9c
LP
923
924DIR *xopendirat(int fd, const char *name, int flags) {
925 int nfd;
926 DIR *d;
927
928 assert(!(flags & O_CREAT));
929
930 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
931 if (nfd < 0)
932 return NULL;
933
934 d = fdopendir(nfd);
935 if (!d) {
936 safe_close(nfd);
937 return NULL;
938 }
939
940 return d;
941}
942
943static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
944 char **i;
945
946 assert(path);
947 assert(mode);
948 assert(_f);
949
950 if (!path_strv_resolve_uniq(search, root))
951 return -ENOMEM;
952
953 STRV_FOREACH(i, search) {
954 _cleanup_free_ char *p = NULL;
955 FILE *f;
956
957 if (root)
958 p = strjoin(root, *i, "/", path, NULL);
959 else
960 p = strjoin(*i, "/", path, NULL);
961 if (!p)
962 return -ENOMEM;
963
964 f = fopen(p, mode);
965 if (f) {
966 *_f = f;
967 return 0;
968 }
969
970 if (errno != ENOENT)
971 return -errno;
972 }
973
974 return -ENOENT;
975}
976
977int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
978 _cleanup_strv_free_ char **copy = NULL;
979
980 assert(path);
981 assert(mode);
982 assert(_f);
983
984 if (path_is_absolute(path)) {
985 FILE *f;
986
987 f = fopen(path, mode);
988 if (f) {
989 *_f = f;
990 return 0;
991 }
992
993 return -errno;
994 }
995
996 copy = strv_copy((char**) search);
997 if (!copy)
998 return -ENOMEM;
999
1000 return search_and_fopen_internal(path, mode, root, copy, _f);
1001}
1002
1003int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
1004 _cleanup_strv_free_ char **s = NULL;
1005
1006 if (path_is_absolute(path)) {
1007 FILE *f;
1008
1009 f = fopen(path, mode);
1010 if (f) {
1011 *_f = f;
1012 return 0;
1013 }
1014
1015 return -errno;
1016 }
1017
1018 s = strv_split_nulstr(search);
1019 if (!s)
1020 return -ENOMEM;
1021
1022 return search_and_fopen_internal(path, mode, root, s, _f);
1023}
1024
1025int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1026 FILE *f;
1027 char *t;
1028 int r, fd;
1029
1030 assert(path);
1031 assert(_f);
1032 assert(_temp_path);
1033
1034 r = tempfn_xxxxxx(path, NULL, &t);
1035 if (r < 0)
1036 return r;
1037
1038 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
1039 if (fd < 0) {
1040 free(t);
1041 return -errno;
1042 }
1043
1044 f = fdopen(fd, "we");
1045 if (!f) {
1046 unlink_noerrno(t);
1047 free(t);
1048 safe_close(fd);
1049 return -errno;
1050 }
1051
1052 *_f = f;
1053 *_temp_path = t;
1054
1055 return 0;
1056}
1057
1058int fflush_and_check(FILE *f) {
1059 assert(f);
1060
1061 errno = 0;
1062 fflush(f);
1063
1064 if (ferror(f))
f5e5c28f 1065 return errno > 0 ? -errno : -EIO;
0d39fa9c
LP
1066
1067 return 0;
1068}
1069
1070/* This is much like like mkostemp() but is subject to umask(). */
1071int mkostemp_safe(char *pattern, int flags) {
1072 _cleanup_umask_ mode_t u;
1073 int fd;
1074
1075 assert(pattern);
1076
1077 u = umask(077);
1078
1079 fd = mkostemp(pattern, flags);
1080 if (fd < 0)
1081 return -errno;
1082
1083 return fd;
1084}
1085
1086int open_tmpfile(const char *path, int flags) {
1087 char *p;
1088 int fd;
1089
1090 assert(path);
1091
1092#ifdef O_TMPFILE
1093 /* Try O_TMPFILE first, if it is supported */
1094 fd = open(path, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1095 if (fd >= 0)
1096 return fd;
1097#endif
1098
1099 /* Fall back to unguessable name + unlinking */
1100 p = strjoina(path, "/systemd-tmp-XXXXXX");
1101
1102 fd = mkostemp_safe(p, flags);
1103 if (fd < 0)
1104 return fd;
1105
1106 unlink(p);
1107 return fd;
1108}
1109
1110int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1111 const char *fn;
1112 char *t;
1113
1114 assert(p);
1115 assert(ret);
1116
1117 /*
1118 * Turns this:
1119 * /foo/bar/waldo
1120 *
1121 * Into this:
1122 * /foo/bar/.#<extra>waldoXXXXXX
1123 */
1124
1125 fn = basename(p);
1126 if (!filename_is_valid(fn))
1127 return -EINVAL;
1128
1129 if (extra == NULL)
1130 extra = "";
1131
1132 t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1133 if (!t)
1134 return -ENOMEM;
1135
1136 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1137
1138 *ret = path_kill_slashes(t);
1139 return 0;
1140}
1141
1142int tempfn_random(const char *p, const char *extra, char **ret) {
1143 const char *fn;
1144 char *t, *x;
1145 uint64_t u;
1146 unsigned i;
1147
1148 assert(p);
1149 assert(ret);
1150
1151 /*
1152 * Turns this:
1153 * /foo/bar/waldo
1154 *
1155 * Into this:
1156 * /foo/bar/.#<extra>waldobaa2a261115984a9
1157 */
1158
1159 fn = basename(p);
1160 if (!filename_is_valid(fn))
1161 return -EINVAL;
1162
1163 if (!extra)
1164 extra = "";
1165
1166 t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1167 if (!t)
1168 return -ENOMEM;
1169
1170 x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1171
1172 u = random_u64();
1173 for (i = 0; i < 16; i++) {
1174 *(x++) = hexchar(u & 0xF);
1175 u >>= 4;
1176 }
1177
1178 *x = 0;
1179
1180 *ret = path_kill_slashes(t);
1181 return 0;
1182}
1183
1184int tempfn_random_child(const char *p, const char *extra, char **ret) {
1185 char *t, *x;
1186 uint64_t u;
1187 unsigned i;
1188
1189 assert(p);
1190 assert(ret);
1191
1192 /* Turns this:
1193 * /foo/bar/waldo
1194 * Into this:
1195 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1196 */
1197
1198 if (!extra)
1199 extra = "";
1200
1201 t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1202 if (!t)
1203 return -ENOMEM;
1204
1205 x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
1206
1207 u = random_u64();
1208 for (i = 0; i < 16; i++) {
1209 *(x++) = hexchar(u & 0xF);
1210 u >>= 4;
1211 }
1212
1213 *x = 0;
1214
1215 *ret = path_kill_slashes(t);
1216 return 0;
1217}
33d52ab9
LP
1218
1219int write_timestamp_file_atomic(const char *fn, usec_t n) {
1220 char ln[DECIMAL_STR_MAX(n)+2];
1221
1222 /* Creates a "timestamp" file, that contains nothing but a
1223 * usec_t timestamp, formatted in ASCII. */
1224
1225 if (n <= 0 || n >= USEC_INFINITY)
1226 return -ERANGE;
1227
1228 xsprintf(ln, USEC_FMT "\n", n);
1229
1230 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1231}
1232
1233int read_timestamp_file(const char *fn, usec_t *ret) {
1234 _cleanup_free_ char *ln = NULL;
1235 uint64_t t;
1236 int r;
1237
1238 r = read_one_line_file(fn, &ln);
1239 if (r < 0)
1240 return r;
1241
1242 r = safe_atou64(ln, &t);
1243 if (r < 0)
1244 return r;
1245
1246 if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1247 return -ERANGE;
1248
1249 *ret = (usec_t) t;
1250 return 0;
1251}
d390f8ef
LP
1252
1253int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1254 int r;
1255
1256 assert(s);
1257
1258 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1259 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1260 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1261 * element, but not before the first one. */
1262
1263 if (!f)
1264 f = stdout;
1265
1266 if (space) {
1267 if (!separator)
1268 separator = " ";
1269
1270 if (*space) {
1271 r = fputs(separator, f);
1272 if (r < 0)
1273 return r;
1274 }
1275
1276 *space = true;
1277 }
1278
1279 return fputs(s, f);
1280}