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