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