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