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