]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/fileio.c
Merge pull request #6636 from sourcejedi/fsync
[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 "env-util.h"
34 #include "escape.h"
35 #include "fd-util.h"
36 #include "fileio.h"
37 #include "fs-util.h"
38 #include "hexdecoct.h"
39 #include "log.h"
40 #include "macro.h"
41 #include "missing.h"
42 #include "parse-util.h"
43 #include "path-util.h"
44 #include "process-util.h"
45 #include "random-util.h"
46 #include "stdio-util.h"
47 #include "string-util.h"
48 #include "strv.h"
49 #include "time-util.h"
50 #include "umask-util.h"
51 #include "utf8.h"
52
53 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
54
55 int write_string_stream_ts(FILE *f, const char *line, bool enforce_newline, struct timespec *ts) {
56
57 assert(f);
58 assert(line);
59
60 fputs(line, f);
61 if (enforce_newline && !endswith(line, "\n"))
62 fputc('\n', f);
63
64 if (ts) {
65 struct timespec twice[2] = {*ts, *ts};
66
67 if (futimens(fileno(f), twice) < 0)
68 return -errno;
69 }
70
71 return fflush_and_check(f);
72 }
73
74 static int write_string_file_atomic(const char *fn, const char *line, bool enforce_newline, bool do_fsync) {
75 _cleanup_fclose_ FILE *f = NULL;
76 _cleanup_free_ char *p = NULL;
77 int r;
78
79 assert(fn);
80 assert(line);
81
82 r = fopen_temporary(fn, &f, &p);
83 if (r < 0)
84 return r;
85
86 (void) fchmod_umask(fileno(f), 0644);
87
88 r = write_string_stream(f, line, enforce_newline);
89 if (r >= 0 && do_fsync)
90 r = fflush_sync_and_check(f);
91
92 if (r >= 0) {
93 if (rename(p, fn) < 0)
94 r = -errno;
95 }
96
97 if (r < 0)
98 (void) unlink(p);
99
100 return r;
101 }
102
103 int write_string_file_ts(const char *fn, const char *line, WriteStringFileFlags flags, struct timespec *ts) {
104 _cleanup_fclose_ FILE *f = NULL;
105 int q, r;
106
107 assert(fn);
108 assert(line);
109
110 /* We don't know how to verify whether the file contents was already on-disk. */
111 assert(!((flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE) && (flags & WRITE_STRING_FILE_SYNC)));
112
113 if (flags & WRITE_STRING_FILE_ATOMIC) {
114 assert(flags & WRITE_STRING_FILE_CREATE);
115
116 r = write_string_file_atomic(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE),
117 flags & WRITE_STRING_FILE_SYNC);
118 if (r < 0)
119 goto fail;
120
121 return r;
122 } else
123 assert(ts == NULL);
124
125 if (flags & WRITE_STRING_FILE_CREATE) {
126 f = fopen(fn, "we");
127 if (!f) {
128 r = -errno;
129 goto fail;
130 }
131 } else {
132 int fd;
133
134 /* We manually build our own version of fopen(..., "we") that
135 * works without O_CREAT */
136 fd = open(fn, O_WRONLY|O_CLOEXEC|O_NOCTTY);
137 if (fd < 0) {
138 r = -errno;
139 goto fail;
140 }
141
142 f = fdopen(fd, "we");
143 if (!f) {
144 r = -errno;
145 safe_close(fd);
146 goto fail;
147 }
148 }
149
150 r = write_string_stream_ts(f, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE), ts);
151 if (r < 0)
152 goto fail;
153
154 if (flags & WRITE_STRING_FILE_SYNC) {
155 r = fflush_sync_and_check(f);
156 if (r < 0)
157 return r;
158 }
159
160 return 0;
161
162 fail:
163 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
164 return r;
165
166 f = safe_fclose(f);
167
168 /* OK, the operation failed, but let's see if the right
169 * contents in place already. If so, eat up the error. */
170
171 q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
172 if (q <= 0)
173 return r;
174
175 return 0;
176 }
177
178 int read_one_line_file(const char *fn, char **line) {
179 _cleanup_fclose_ FILE *f = NULL;
180 char t[LINE_MAX], *c;
181
182 assert(fn);
183 assert(line);
184
185 f = fopen(fn, "re");
186 if (!f)
187 return -errno;
188
189 if (!fgets(t, sizeof(t), f)) {
190
191 if (ferror(f))
192 return errno > 0 ? -errno : -EIO;
193
194 t[0] = 0;
195 }
196
197 c = strdup(t);
198 if (!c)
199 return -ENOMEM;
200 truncate_nl(c);
201
202 *line = c;
203 return 0;
204 }
205
206 int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
207 _cleanup_fclose_ FILE *f = NULL;
208 _cleanup_free_ char *buf = NULL;
209 size_t l, k;
210
211 assert(fn);
212 assert(blob);
213
214 l = strlen(blob);
215
216 if (accept_extra_nl && endswith(blob, "\n"))
217 accept_extra_nl = false;
218
219 buf = malloc(l + accept_extra_nl + 1);
220 if (!buf)
221 return -ENOMEM;
222
223 f = fopen(fn, "re");
224 if (!f)
225 return -errno;
226
227 /* We try to read one byte more than we need, so that we know whether we hit eof */
228 errno = 0;
229 k = fread(buf, 1, l + accept_extra_nl + 1, f);
230 if (ferror(f))
231 return errno > 0 ? -errno : -EIO;
232
233 if (k != l && k != l + accept_extra_nl)
234 return 0;
235 if (memcmp(buf, blob, l) != 0)
236 return 0;
237 if (k > l && buf[l] != '\n')
238 return 0;
239
240 return 1;
241 }
242
243 int read_full_stream(FILE *f, char **contents, size_t *size) {
244 size_t n, l;
245 _cleanup_free_ char *buf = NULL;
246 struct stat st;
247
248 assert(f);
249 assert(contents);
250
251 if (fstat(fileno(f), &st) < 0)
252 return -errno;
253
254 n = LINE_MAX;
255
256 if (S_ISREG(st.st_mode)) {
257
258 /* Safety check */
259 if (st.st_size > READ_FULL_BYTES_MAX)
260 return -E2BIG;
261
262 /* Start with the right file size, but be prepared for
263 * files from /proc which generally report a file size
264 * of 0 */
265 if (st.st_size > 0)
266 n = st.st_size;
267 }
268
269 l = 0;
270 for (;;) {
271 char *t;
272 size_t k;
273
274 t = realloc(buf, n + 1);
275 if (!t)
276 return -ENOMEM;
277
278 buf = t;
279 k = fread(buf + l, 1, n - l, f);
280 if (k > 0)
281 l += k;
282
283 if (ferror(f))
284 return -errno;
285
286 if (feof(f))
287 break;
288
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);
293
294 /* Safety check */
295 if (n >= READ_FULL_BYTES_MAX)
296 return -E2BIG;
297
298 n = MIN(n * 2, READ_FULL_BYTES_MAX);
299 }
300
301 buf[l] = 0;
302 *contents = buf;
303 buf = NULL; /* do not free */
304
305 if (size)
306 *size = l;
307
308 return 0;
309 }
310
311 int 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
324 static int parse_env_file_internal(
325 FILE *f,
326 const char *fname,
327 const char *newline,
328 int (*push) (const char *filename, unsigned line,
329 const char *key, char *value, void *userdata, int *n_pushed),
330 void *userdata,
331 int *n_pushed) {
332
333 _cleanup_free_ char *contents = NULL, *key = NULL;
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;
335 char *p, *value = NULL;
336 int r;
337 unsigned line = 1;
338
339 enum {
340 PRE_KEY,
341 KEY,
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;
352
353 assert(newline);
354
355 if (f)
356 r = read_full_stream(f, &contents, NULL);
357 else
358 r = read_full_file(fname, &contents, NULL);
359 if (r < 0)
360 return r;
361
362 for (p = contents; *p; p++) {
363 char c = *p;
364
365 switch (state) {
366
367 case PRE_KEY:
368 if (strchr(COMMENTS, c))
369 state = COMMENT;
370 else if (!strchr(WHITESPACE, c)) {
371 state = KEY;
372 last_key_whitespace = (size_t) -1;
373
374 if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) {
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;
386 line++;
387 n_key = 0;
388 } else if (c == '=') {
389 state = PRE_VALUE;
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
397 if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) {
398 r = -ENOMEM;
399 goto fail;
400 }
401
402 key[n_key++] = c;
403 }
404
405 break;
406
407 case PRE_VALUE:
408 if (strchr(newline, c)) {
409 state = PRE_KEY;
410 line++;
411 key[n_key] = 0;
412
413 if (value)
414 value[n_value] = 0;
415
416 /* strip trailing whitespace from key */
417 if (last_key_whitespace != (size_t) -1)
418 key[last_key_whitespace] = 0;
419
420 r = push(fname, line, key, value, userdata, n_pushed);
421 if (r < 0)
422 goto fail;
423
424 n_key = 0;
425 value = NULL;
426 value_alloc = n_value = 0;
427
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
437 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
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;
450 line++;
451
452 key[n_key] = 0;
453
454 if (value)
455 value[n_value] = 0;
456
457 /* Chomp off trailing whitespace from value */
458 if (last_value_whitespace != (size_t) -1)
459 value[last_value_whitespace] = 0;
460
461 /* strip trailing whitespace from key */
462 if (last_key_whitespace != (size_t) -1)
463 key[last_key_whitespace] = 0;
464
465 r = push(fname, line, key, value, userdata, n_pushed);
466 if (r < 0)
467 goto fail;
468
469 n_key = 0;
470 value = NULL;
471 value_alloc = n_value = 0;
472
473 } else if (c == '\\') {
474 state = VALUE_ESCAPE;
475 last_value_whitespace = (size_t) -1;
476 } else {
477 if (!strchr(WHITESPACE, c))
478 last_value_whitespace = (size_t) -1;
479 else if (last_value_whitespace == (size_t) -1)
480 last_value_whitespace = n_value;
481
482 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
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 */
497 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
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 {
512 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
513 r = -ENOMEM;
514 goto fail;
515 }
516
517 value[n_value++] = c;
518 }
519
520 break;
521
522 case SINGLE_QUOTE_VALUE_ESCAPE:
523 state = SINGLE_QUOTE_VALUE;
524
525 if (!strchr(newline, c)) {
526 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
527 r = -ENOMEM;
528 goto fail;
529 }
530
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 {
541 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
542 r = -ENOMEM;
543 goto fail;
544 }
545
546 value[n_value++] = c;
547 }
548
549 break;
550
551 case DOUBLE_QUOTE_VALUE_ESCAPE:
552 state = DOUBLE_QUOTE_VALUE;
553
554 if (!strchr(newline, c)) {
555 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
556 r = -ENOMEM;
557 goto fail;
558 }
559
560 value[n_value++] = c;
561 }
562 break;
563
564 case COMMENT:
565 if (c == '\\')
566 state = COMMENT_ESCAPE;
567 else if (strchr(newline, c)) {
568 state = PRE_KEY;
569 line++;
570 }
571 break;
572
573 case COMMENT_ESCAPE:
574 state = COMMENT;
575 break;
576 }
577 }
578
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)) {
587
588 key[n_key] = 0;
589
590 if (value)
591 value[n_value] = 0;
592
593 if (state == VALUE)
594 if (last_value_whitespace != (size_t) -1)
595 value[last_value_whitespace] = 0;
596
597 /* strip trailing whitespace from key */
598 if (last_key_whitespace != (size_t) -1)
599 key[last_key_whitespace] = 0;
600
601 r = push(fname, line, key, value, userdata, n_pushed);
602 if (r < 0)
603 goto fail;
604 }
605
606 return 0;
607
608 fail:
609 free(value);
610 return r;
611 }
612
613 static int check_utf8ness_and_warn(
614 const char *filename, unsigned line,
615 const char *key, char *value) {
616
617 if (!utf8_is_valid(key)) {
618 _cleanup_free_ char *p = NULL;
619
620 p = utf8_escape_invalid(key);
621 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p);
622 return -EINVAL;
623 }
624
625 if (value && !utf8_is_valid(value)) {
626 _cleanup_free_ char *p = NULL;
627
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);
630 return -EINVAL;
631 }
632
633 return 0;
634 }
635
636 static 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
650 va_copy(aq, *ap);
651
652 while ((k = va_arg(aq, const char *))) {
653 char **v;
654
655 v = va_arg(aq, char **);
656
657 if (streq(key, k)) {
658 va_end(aq);
659 free(*v);
660 *v = value;
661
662 if (n_pushed)
663 (*n_pushed)++;
664
665 return 1;
666 }
667 }
668
669 va_end(aq);
670 free(value);
671
672 return 0;
673 }
674
675 int parse_env_file(
676 const char *fname,
677 const char *newline, ...) {
678
679 va_list ap;
680 int r, n_pushed = 0;
681
682 if (!newline)
683 newline = NEWLINE;
684
685 va_start(ap, newline);
686 r = parse_env_file_internal(NULL, fname, newline, parse_env_file_push, &ap, &n_pushed);
687 va_end(ap);
688
689 return r < 0 ? r : n_pushed;
690 }
691
692 static int load_env_file_push(
693 const char *filename, unsigned line,
694 const char *key, char *value,
695 void *userdata,
696 int *n_pushed) {
697 char ***m = userdata;
698 char *p;
699 int r;
700
701 r = check_utf8ness_and_warn(filename, line, key, value);
702 if (r < 0)
703 return r;
704
705 p = strjoin(key, "=", value);
706 if (!p)
707 return -ENOMEM;
708
709 r = strv_env_replace(m, p);
710 if (r < 0) {
711 free(p);
712 return r;
713 }
714
715 if (n_pushed)
716 (*n_pushed)++;
717
718 free(value);
719 return 0;
720 }
721
722 int 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
729 r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
730 if (r < 0) {
731 strv_free(m);
732 return r;
733 }
734
735 *rl = m;
736 return 0;
737 }
738
739 static int load_env_file_push_pairs(
740 const char *filename, unsigned line,
741 const char *key, char *value,
742 void *userdata,
743 int *n_pushed) {
744 char ***m = userdata;
745 int r;
746
747 r = check_utf8ness_and_warn(filename, line, key, value);
748 if (r < 0)
749 return r;
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
765 if (n_pushed)
766 (*n_pushed)++;
767
768 return 0;
769 }
770
771 int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
772 char **m = NULL;
773 int r;
774
775 if (!newline)
776 newline = NEWLINE;
777
778 r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
779 if (r < 0) {
780 strv_free(m);
781 return r;
782 }
783
784 *rl = m;
785 return 0;
786 }
787
788 static 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
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);
806 free(value);
807 return 0;
808 }
809
810 expanded_value = replace_env(value, *env,
811 REPLACE_ENV_USE_ENVIRONMENT|
812 REPLACE_ENV_ALLOW_BRACELESS|
813 REPLACE_ENV_ALLOW_EXTENDED);
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
822 int merge_env_file(
823 char ***env,
824 FILE *f,
825 const char *fname) {
826
827 /* NOTE: this function supports braceful and braceless variable expansions,
828 * plus "extended" substitutions, unlike other exported parsing functions.
829 */
830
831 return parse_env_file_internal(f, fname, NEWLINE, merge_env_file_push, env, NULL);
832 }
833
834 static void write_env_var(FILE *f, const char *v) {
835 const char *p;
836
837 p = strchr(v, '=');
838 if (!p) {
839 /* Fallback */
840 fputs_unlocked(v, f);
841 fputc_unlocked('\n', f);
842 return;
843 }
844
845 p++;
846 fwrite_unlocked(v, 1, p-v, f);
847
848 if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
849 fputc_unlocked('\"', f);
850
851 for (; *p; p++) {
852 if (strchr(SHELL_NEED_ESCAPE, *p))
853 fputc_unlocked('\\', f);
854
855 fputc_unlocked(*p, f);
856 }
857
858 fputc_unlocked('\"', f);
859 } else
860 fputs_unlocked(p, f);
861
862 fputc_unlocked('\n', f);
863 }
864
865 int write_env_file(const char *fname, char **l) {
866 _cleanup_fclose_ FILE *f = NULL;
867 _cleanup_free_ char *p = NULL;
868 char **i;
869 int r;
870
871 assert(fname);
872
873 r = fopen_temporary(fname, &f, &p);
874 if (r < 0)
875 return r;
876
877 fchmod_umask(fileno(f), 0644);
878
879 STRV_FOREACH(i, l)
880 write_env_var(f, *i);
881
882 r = fflush_and_check(f);
883 if (r >= 0) {
884 if (rename(p, fname) >= 0)
885 return 0;
886
887 r = -errno;
888 }
889
890 unlink(p);
891 return r;
892 }
893
894 int executable_is_script(const char *path, char **interpreter) {
895 int r;
896 _cleanup_free_ char *line = NULL;
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 }
922
923 /**
924 * Retrieve one field from a file like /proc/self/status. pattern
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).
930 */
931 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
932 _cleanup_free_ char *status = NULL;
933 char *t, *f;
934 size_t len;
935 int r;
936
937 assert(terminator);
938 assert(filename);
939 assert(pattern);
940 assert(field);
941
942 r = read_full_file(filename, &status, NULL);
943 if (r < 0)
944 return r;
945
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++;
970
971 if (*t) {
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");
980 /* Back off one char if there's nothing but whitespace
981 and zeros */
982 if (!*t || isspace(*t))
983 t--;
984 }
985
986 len = strcspn(t, terminator);
987
988 f = strndup(t, len);
989 if (!f)
990 return -ENOMEM;
991
992 *field = f;
993 return 0;
994 }
995
996 DIR *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
1015 static 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)
1030 p = strjoin(root, *i, "/", path);
1031 else
1032 p = strjoin(*i, "/", path);
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
1049 int 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
1075 int 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
1097 int 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
1110 fd = mkostemp_safe(t);
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
1130 int fflush_and_check(FILE *f) {
1131 assert(f);
1132
1133 errno = 0;
1134 fflush(f);
1135
1136 if (ferror(f))
1137 return errno > 0 ? -errno : -EIO;
1138
1139 return 0;
1140 }
1141
1142 int 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
1157 /* This is much like mkostemp() but is subject to umask(). */
1158 int mkostemp_safe(char *pattern) {
1159 _cleanup_umask_ mode_t u = 0;
1160 int fd;
1161
1162 assert(pattern);
1163
1164 u = umask(077);
1165
1166 fd = mkostemp(pattern, O_CLOEXEC);
1167 if (fd < 0)
1168 return -errno;
1169
1170 return fd;
1171 }
1172
1173 int 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
1205 int 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
1247 int tempfn_random_child(const char *p, const char *extra, char **ret) {
1248 char *t, *x;
1249 uint64_t u;
1250 unsigned i;
1251 int r;
1252
1253 assert(ret);
1254
1255 /* Turns this:
1256 * /foo/bar/waldo
1257 * Into this:
1258 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1259 */
1260
1261 if (!p) {
1262 r = tmp_dir(&p);
1263 if (r < 0)
1264 return r;
1265 }
1266
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 }
1287
1288 int 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
1302 int 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 }
1321
1322 int 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 }
1350
1351 int open_tmpfile_unlinkable(const char *directory, int flags) {
1352 char *p;
1353 int fd, r;
1354
1355 if (!directory) {
1356 r = tmp_dir(&directory);
1357 if (r < 0)
1358 return r;
1359 }
1360
1361 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1362
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;
1367
1368 /* Fall back to unguessable name + unlinking */
1369 p = strjoina(directory, "/systemd-tmp-XXXXXX");
1370
1371 fd = mkostemp_safe(p);
1372 if (fd < 0)
1373 return fd;
1374
1375 (void) unlink(p);
1376
1377 return fd;
1378 }
1379
1380 int 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
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 }
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
1424 int 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
1431 path = getpid_cached() == 1 ? "/run/systemd" : "/tmp";
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
1443 int 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 *
1452 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
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 }
1469
1470 int 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 }
1510
1511 int 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 }