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