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