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