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