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