chiark / gitweb /
43c804472feb870c788020728f09b2e7d9c2632e
[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_file(
680                 const char *fname,
681                 const char *newline, ...) {
682
683         va_list ap;
684         int r, n_pushed = 0;
685
686         if (!newline)
687                 newline = NEWLINE;
688
689         va_start(ap, newline);
690         r = parse_env_file_internal(NULL, fname, newline, parse_env_file_push, &ap, &n_pushed);
691         va_end(ap);
692
693         return r < 0 ? r : n_pushed;
694 }
695
696 #if 0 /// UNNEEDED by elogind
697 static int load_env_file_push(
698                 const char *filename, unsigned line,
699                 const char *key, char *value,
700                 void *userdata,
701                 int *n_pushed) {
702         char ***m = userdata;
703         char *p;
704         int r;
705
706         r = check_utf8ness_and_warn(filename, line, key, value);
707         if (r < 0)
708                 return r;
709
710         p = strjoin(key, "=", value);
711         if (!p)
712                 return -ENOMEM;
713
714         r = strv_env_replace(m, p);
715         if (r < 0) {
716                 free(p);
717                 return r;
718         }
719
720         if (n_pushed)
721                 (*n_pushed)++;
722
723         free(value);
724         return 0;
725 }
726
727 int load_env_file(FILE *f, const char *fname, const char *newline, char ***rl) {
728         char **m = NULL;
729         int r;
730
731         if (!newline)
732                 newline = NEWLINE;
733
734         r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
735         if (r < 0) {
736                 strv_free(m);
737                 return r;
738         }
739
740         *rl = m;
741         return 0;
742 }
743 #endif // 0
744
745 static int load_env_file_push_pairs(
746                 const char *filename, unsigned line,
747                 const char *key, char *value,
748                 void *userdata,
749                 int *n_pushed) {
750         char ***m = userdata;
751         int r;
752
753         r = check_utf8ness_and_warn(filename, line, key, value);
754         if (r < 0)
755                 return r;
756
757         r = strv_extend(m, key);
758         if (r < 0)
759                 return -ENOMEM;
760
761         if (!value) {
762                 r = strv_extend(m, "");
763                 if (r < 0)
764                         return -ENOMEM;
765         } else {
766                 r = strv_push(m, value);
767                 if (r < 0)
768                         return r;
769         }
770
771         if (n_pushed)
772                 (*n_pushed)++;
773
774         return 0;
775 }
776
777 int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
778         char **m = NULL;
779         int r;
780
781         if (!newline)
782                 newline = NEWLINE;
783
784         r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
785         if (r < 0) {
786                 strv_free(m);
787                 return r;
788         }
789
790         *rl = m;
791         return 0;
792 }
793 #if 0 /// UNNEEDED by elogind
794
795 static int merge_env_file_push(
796                 const char *filename, unsigned line,
797                 const char *key, char *value,
798                 void *userdata,
799                 int *n_pushed) {
800
801         char ***env = userdata;
802         char *expanded_value;
803
804         assert(env);
805
806         if (!value) {
807                 log_error("%s:%u: invalid syntax (around \"%s\"), ignoring.", strna(filename), line, key);
808                 return 0;
809         }
810
811         if (!env_name_is_valid(key)) {
812                 log_error("%s:%u: invalid variable name \"%s\", ignoring.", strna(filename), line, key);
813                 free(value);
814                 return 0;
815         }
816
817         expanded_value = replace_env(value, *env,
818                                      REPLACE_ENV_USE_ENVIRONMENT|
819                                      REPLACE_ENV_ALLOW_BRACELESS|
820                                      REPLACE_ENV_ALLOW_EXTENDED);
821         if (!expanded_value)
822                 return -ENOMEM;
823
824         free_and_replace(value, expanded_value);
825
826         return load_env_file_push(filename, line, key, value, env, n_pushed);
827 }
828
829 int merge_env_file(
830                 char ***env,
831                 FILE *f,
832                 const char *fname) {
833
834         /* NOTE: this function supports braceful and braceless variable expansions,
835          * plus "extended" substitutions, unlike other exported parsing functions.
836          */
837
838         return parse_env_file_internal(f, fname, NEWLINE, merge_env_file_push, env, NULL);
839 }
840
841 static void write_env_var(FILE *f, const char *v) {
842         const char *p;
843
844         p = strchr(v, '=');
845         if (!p) {
846                 /* Fallback */
847                 fputs_unlocked(v, f);
848                 fputc_unlocked('\n', f);
849                 return;
850         }
851
852         p++;
853         fwrite_unlocked(v, 1, p-v, f);
854
855         if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
856                 fputc_unlocked('\"', f);
857
858                 for (; *p; p++) {
859                         if (strchr(SHELL_NEED_ESCAPE, *p))
860                                 fputc_unlocked('\\', f);
861
862                         fputc_unlocked(*p, f);
863                 }
864
865                 fputc_unlocked('\"', f);
866         } else
867                 fputs_unlocked(p, f);
868
869         fputc_unlocked('\n', f);
870 }
871
872 int write_env_file(const char *fname, char **l) {
873         _cleanup_fclose_ FILE *f = NULL;
874         _cleanup_free_ char *p = NULL;
875         char **i;
876         int r;
877
878         assert(fname);
879
880         r = fopen_temporary(fname, &f, &p);
881         if (r < 0)
882                 return r;
883
884         (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
885         (void) fchmod_umask(fileno(f), 0644);
886
887         STRV_FOREACH(i, l)
888                 write_env_var(f, *i);
889
890         r = fflush_and_check(f);
891         if (r >= 0) {
892                 if (rename(p, fname) >= 0)
893                         return 0;
894
895                 r = -errno;
896         }
897
898         unlink(p);
899         return r;
900 }
901
902 int executable_is_script(const char *path, char **interpreter) {
903         _cleanup_free_ char *line = NULL;
904         size_t len;
905         char *ans;
906         int r;
907
908         assert(path);
909
910         r = read_one_line_file(path, &line);
911         if (r == -ENOBUFS) /* First line overly long? if so, then it's not a script */
912                 return 0;
913         if (r < 0)
914                 return r;
915
916         if (!startswith(line, "#!"))
917                 return 0;
918
919         ans = strstrip(line + 2);
920         len = strcspn(ans, " \t");
921
922         if (len == 0)
923                 return 0;
924
925         ans = strndup(ans, len);
926         if (!ans)
927                 return -ENOMEM;
928
929         *interpreter = ans;
930         return 1;
931 }
932 #endif // 0
933
934 /**
935  * Retrieve one field from a file like /proc/self/status.  pattern
936  * should not include whitespace or the delimiter (':'). pattern matches only
937  * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
938  * zeros after the ':' will be skipped. field must be freed afterwards.
939  * terminator specifies the terminating characters of the field value (not
940  * included in the value).
941  */
942 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
943         _cleanup_free_ char *status = NULL;
944         char *t, *f;
945         size_t len;
946         int r;
947
948         assert(terminator);
949         assert(filename);
950         assert(pattern);
951         assert(field);
952
953         r = read_full_file(filename, &status, NULL);
954         if (r < 0)
955                 return r;
956
957         t = status;
958
959         do {
960                 bool pattern_ok;
961
962                 do {
963                         t = strstr(t, pattern);
964                         if (!t)
965                                 return -ENOENT;
966
967                         /* Check that pattern occurs in beginning of line. */
968                         pattern_ok = (t == status || t[-1] == '\n');
969
970                         t += strlen(pattern);
971
972                 } while (!pattern_ok);
973
974                 t += strspn(t, " \t");
975                 if (!*t)
976                         return -ENOENT;
977
978         } while (*t != ':');
979
980         t++;
981
982         if (*t) {
983                 t += strspn(t, " \t");
984
985                 /* Also skip zeros, because when this is used for
986                  * capabilities, we don't want the zeros. This way the
987                  * same capability set always maps to the same string,
988                  * irrespective of the total capability set size. For
989                  * other numbers it shouldn't matter. */
990                 t += strspn(t, "0");
991                 /* Back off one char if there's nothing but whitespace
992                    and zeros */
993                 if (!*t || isspace(*t))
994                         t--;
995         }
996
997         len = strcspn(t, terminator);
998
999         f = strndup(t, len);
1000         if (!f)
1001                 return -ENOMEM;
1002
1003         *field = f;
1004         return 0;
1005 }
1006
1007 DIR *xopendirat(int fd, const char *name, int flags) {
1008         int nfd;
1009         DIR *d;
1010
1011         assert(!(flags & O_CREAT));
1012
1013         nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
1014         if (nfd < 0)
1015                 return NULL;
1016
1017         d = fdopendir(nfd);
1018         if (!d) {
1019                 safe_close(nfd);
1020                 return NULL;
1021         }
1022
1023         return d;
1024 }
1025
1026 #if 0 /// UNNEEDED by elogind
1027 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
1028         char **i;
1029
1030         assert(path);
1031         assert(mode);
1032         assert(_f);
1033
1034         if (!path_strv_resolve_uniq(search, root))
1035                 return -ENOMEM;
1036
1037         STRV_FOREACH(i, search) {
1038                 _cleanup_free_ char *p = NULL;
1039                 FILE *f;
1040
1041                 if (root)
1042                         p = strjoin(root, *i, "/", path);
1043                 else
1044                         p = strjoin(*i, "/", path);
1045                 if (!p)
1046                         return -ENOMEM;
1047
1048                 f = fopen(p, mode);
1049                 if (f) {
1050                         *_f = f;
1051                         return 0;
1052                 }
1053
1054                 if (errno != ENOENT)
1055                         return -errno;
1056         }
1057
1058         return -ENOENT;
1059 }
1060
1061 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
1062         _cleanup_strv_free_ char **copy = NULL;
1063
1064         assert(path);
1065         assert(mode);
1066         assert(_f);
1067
1068         if (path_is_absolute(path)) {
1069                 FILE *f;
1070
1071                 f = fopen(path, mode);
1072                 if (f) {
1073                         *_f = f;
1074                         return 0;
1075                 }
1076
1077                 return -errno;
1078         }
1079
1080         copy = strv_copy((char**) search);
1081         if (!copy)
1082                 return -ENOMEM;
1083
1084         return search_and_fopen_internal(path, mode, root, copy, _f);
1085 }
1086
1087 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
1088         _cleanup_strv_free_ char **s = NULL;
1089
1090         if (path_is_absolute(path)) {
1091                 FILE *f;
1092
1093                 f = fopen(path, mode);
1094                 if (f) {
1095                         *_f = f;
1096                         return 0;
1097                 }
1098
1099                 return -errno;
1100         }
1101
1102         s = strv_split_nulstr(search);
1103         if (!s)
1104                 return -ENOMEM;
1105
1106         return search_and_fopen_internal(path, mode, root, s, _f);
1107 }
1108 #endif // 0
1109
1110 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1111         FILE *f;
1112         char *t;
1113         int r, fd;
1114
1115         assert(path);
1116         assert(_f);
1117         assert(_temp_path);
1118
1119         r = tempfn_xxxxxx(path, NULL, &t);
1120         if (r < 0)
1121                 return r;
1122
1123         fd = mkostemp_safe(t);
1124         if (fd < 0) {
1125                 free(t);
1126                 return -errno;
1127         }
1128
1129         f = fdopen(fd, "we");
1130         if (!f) {
1131                 unlink_noerrno(t);
1132                 free(t);
1133                 safe_close(fd);
1134                 return -errno;
1135         }
1136
1137         *_f = f;
1138         *_temp_path = t;
1139
1140         return 0;
1141 }
1142
1143 int fflush_and_check(FILE *f) {
1144         assert(f);
1145
1146         errno = 0;
1147         fflush(f);
1148
1149         if (ferror(f))
1150                 return errno > 0 ? -errno : -EIO;
1151
1152         return 0;
1153 }
1154
1155 int fflush_sync_and_check(FILE *f) {
1156         int r;
1157
1158         assert(f);
1159
1160         r = fflush_and_check(f);
1161         if (r < 0)
1162                 return r;
1163
1164         if (fsync(fileno(f)) < 0)
1165                 return -errno;
1166
1167         r = fsync_directory_of_file(fileno(f));
1168         if (r < 0)
1169                 return r;
1170
1171         return 0;
1172 }
1173
1174 /* This is much like mkostemp() but is subject to umask(). */
1175 int mkostemp_safe(char *pattern) {
1176         _cleanup_umask_ mode_t u = 0;
1177         int fd;
1178
1179         assert(pattern);
1180
1181         u = umask(077);
1182
1183         fd = mkostemp(pattern, O_CLOEXEC);
1184         if (fd < 0)
1185                 return -errno;
1186
1187         return fd;
1188 }
1189
1190 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1191         const char *fn;
1192         char *t;
1193
1194         assert(p);
1195         assert(ret);
1196
1197         /*
1198          * Turns this:
1199          *         /foo/bar/waldo
1200          *
1201          * Into this:
1202          *         /foo/bar/.#<extra>waldoXXXXXX
1203          */
1204
1205         fn = basename(p);
1206         if (!filename_is_valid(fn))
1207                 return -EINVAL;
1208
1209         extra = strempty(extra);
1210
1211         t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1212         if (!t)
1213                 return -ENOMEM;
1214
1215         strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1216
1217         *ret = path_kill_slashes(t);
1218         return 0;
1219 }
1220
1221 int tempfn_random(const char *p, const char *extra, char **ret) {
1222         const char *fn;
1223         char *t, *x;
1224         uint64_t u;
1225         unsigned i;
1226
1227         assert(p);
1228         assert(ret);
1229
1230         /*
1231          * Turns this:
1232          *         /foo/bar/waldo
1233          *
1234          * Into this:
1235          *         /foo/bar/.#<extra>waldobaa2a261115984a9
1236          */
1237
1238         fn = basename(p);
1239         if (!filename_is_valid(fn))
1240                 return -EINVAL;
1241
1242         extra = strempty(extra);
1243
1244         t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1245         if (!t)
1246                 return -ENOMEM;
1247
1248         x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1249
1250         u = random_u64();
1251         for (i = 0; i < 16; i++) {
1252                 *(x++) = hexchar(u & 0xF);
1253                 u >>= 4;
1254         }
1255
1256         *x = 0;
1257
1258         *ret = path_kill_slashes(t);
1259         return 0;
1260 }
1261
1262 #if 0 /// UNNEEDED by elogind
1263 int tempfn_random_child(const char *p, const char *extra, char **ret) {
1264         char *t, *x;
1265         uint64_t u;
1266         unsigned i;
1267         int r;
1268
1269         assert(ret);
1270
1271         /* Turns this:
1272          *         /foo/bar/waldo
1273          * Into this:
1274          *         /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1275          */
1276
1277         if (!p) {
1278                 r = tmp_dir(&p);
1279                 if (r < 0)
1280                         return r;
1281         }
1282
1283         extra = strempty(extra);
1284
1285         t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1286         if (!t)
1287                 return -ENOMEM;
1288
1289         x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
1290
1291         u = random_u64();
1292         for (i = 0; i < 16; i++) {
1293                 *(x++) = hexchar(u & 0xF);
1294                 u >>= 4;
1295         }
1296
1297         *x = 0;
1298
1299         *ret = path_kill_slashes(t);
1300         return 0;
1301 }
1302
1303 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1304         char ln[DECIMAL_STR_MAX(n)+2];
1305
1306         /* Creates a "timestamp" file, that contains nothing but a
1307          * usec_t timestamp, formatted in ASCII. */
1308
1309         if (n <= 0 || n >= USEC_INFINITY)
1310                 return -ERANGE;
1311
1312         xsprintf(ln, USEC_FMT "\n", n);
1313
1314         return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1315 }
1316
1317 int read_timestamp_file(const char *fn, usec_t *ret) {
1318         _cleanup_free_ char *ln = NULL;
1319         uint64_t t;
1320         int r;
1321
1322         r = read_one_line_file(fn, &ln);
1323         if (r < 0)
1324                 return r;
1325
1326         r = safe_atou64(ln, &t);
1327         if (r < 0)
1328                 return r;
1329
1330         if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1331                 return -ERANGE;
1332
1333         *ret = (usec_t) t;
1334         return 0;
1335 }
1336
1337 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1338         int r;
1339
1340         assert(s);
1341
1342         /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1343          * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1344          * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1345          * element, but not before the first one. */
1346
1347         if (!f)
1348                 f = stdout;
1349
1350         if (space) {
1351                 if (!separator)
1352                         separator = " ";
1353
1354                 if (*space) {
1355                         r = fputs(separator, f);
1356                         if (r < 0)
1357                                 return r;
1358                 }
1359
1360                 *space = true;
1361         }
1362
1363         return fputs(s, f);
1364 }
1365 #endif // 0
1366
1367 int open_tmpfile_unlinkable(const char *directory, int flags) {
1368         char *p;
1369         int fd, r;
1370
1371         if (!directory) {
1372                 r = tmp_dir(&directory);
1373                 if (r < 0)
1374                         return r;
1375         }
1376
1377         /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1378
1379         /* Try O_TMPFILE first, if it is supported */
1380         fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1381         if (fd >= 0)
1382                 return fd;
1383
1384         /* Fall back to unguessable name + unlinking */
1385         p = strjoina(directory, "/systemd-tmp-XXXXXX");
1386
1387         fd = mkostemp_safe(p);
1388         if (fd < 0)
1389                 return fd;
1390
1391         (void) unlink(p);
1392
1393         return fd;
1394 }
1395
1396 #if 0 /// UNNEEDED by elogind
1397 int open_tmpfile_linkable(const char *target, int flags, char **ret_path) {
1398         _cleanup_free_ char *tmp = NULL;
1399         int r, fd;
1400
1401         assert(target);
1402         assert(ret_path);
1403
1404         /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1405         assert((flags & O_EXCL) == 0);
1406
1407         /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1408          * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1409          * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1410
1411         {
1412                 _cleanup_free_ char *dn = NULL;
1413
1414                 dn = dirname_malloc(target);
1415                 if (!dn)
1416                         return -ENOMEM;
1417
1418                 fd = open(dn, O_TMPFILE|flags, 0640);
1419                 if (fd >= 0) {
1420                         *ret_path = NULL;
1421                         return fd;
1422                 }
1423
1424                 log_debug_errno(errno, "Failed to use O_TMPFILE on %s: %m", dn);
1425         }
1426
1427         r = tempfn_random(target, NULL, &tmp);
1428         if (r < 0)
1429                 return r;
1430
1431         fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640);
1432         if (fd < 0)
1433                 return -errno;
1434
1435         *ret_path = TAKE_PTR(tmp);
1436
1437         return fd;
1438 }
1439 #endif // 0
1440
1441 int open_serialization_fd(const char *ident) {
1442         int fd = -1;
1443
1444         fd = memfd_create(ident, MFD_CLOEXEC);
1445         if (fd < 0) {
1446                 const char *path;
1447
1448                 path = getpid_cached() == 1 ? "/run/systemd" : "/tmp";
1449                 fd = open_tmpfile_unlinkable(path, O_RDWR|O_CLOEXEC);
1450                 if (fd < 0)
1451                         return fd;
1452
1453                 log_debug("Serializing %s to %s.", ident, path);
1454         } else
1455                 log_debug("Serializing %s to memfd.", ident);
1456
1457         return fd;
1458 }
1459
1460 #if 0 /// UNNEEDED by elogind
1461 int link_tmpfile(int fd, const char *path, const char *target) {
1462
1463         assert(fd >= 0);
1464         assert(target);
1465
1466         /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1467          * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1468          * on the directory, and renameat2() is used instead.
1469          *
1470          * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1471          * operation currently (renameat2() does), and there is no nice way to emulate this. */
1472
1473         if (path) {
1474                 if (rename_noreplace(AT_FDCWD, path, AT_FDCWD, target) < 0)
1475                         return -errno;
1476         } else {
1477                 char proc_fd_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
1478
1479                 xsprintf(proc_fd_path, "/proc/self/fd/%i", fd);
1480
1481                 if (linkat(AT_FDCWD, proc_fd_path, AT_FDCWD, target, AT_SYMLINK_FOLLOW) < 0)
1482                         return -errno;
1483         }
1484
1485         return 0;
1486 }
1487
1488 int read_nul_string(FILE *f, char **ret) {
1489         _cleanup_free_ char *x = NULL;
1490         size_t allocated = 0, n = 0;
1491
1492         assert(f);
1493         assert(ret);
1494
1495         /* Reads a NUL-terminated string from the specified file. */
1496
1497         for (;;) {
1498                 int c;
1499
1500                 if (!GREEDY_REALLOC(x, allocated, n+2))
1501                         return -ENOMEM;
1502
1503                 c = fgetc(f);
1504                 if (c == 0) /* Terminate at NUL byte */
1505                         break;
1506                 if (c == EOF) {
1507                         if (ferror(f))
1508                                 return -errno;
1509                         break; /* Terminate at EOF */
1510                 }
1511
1512                 x[n++] = (char) c;
1513         }
1514
1515         if (x)
1516                 x[n] = 0;
1517         else {
1518                 x = new0(char, 1);
1519                 if (!x)
1520                         return -ENOMEM;
1521         }
1522
1523         *ret = TAKE_PTR(x);
1524
1525         return 0;
1526 }
1527
1528 int mkdtemp_malloc(const char *template, char **ret) {
1529         char *p;
1530
1531         assert(template);
1532         assert(ret);
1533
1534         p = strdup(template);
1535         if (!p)
1536                 return -ENOMEM;
1537
1538         if (!mkdtemp(p)) {
1539                 free(p);
1540                 return -errno;
1541         }
1542
1543         *ret = p;
1544         return 0;
1545 }
1546 #endif // 0
1547
1548 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile);
1549
1550 int read_line(FILE *f, size_t limit, char **ret) {
1551         _cleanup_free_ char *buffer = NULL;
1552         size_t n = 0, allocated = 0, count = 0;
1553
1554         assert(f);
1555
1556         /* Something like a bounded version of getline().
1557          *
1558          * Considers EOF, \n and \0 end of line delimiters, and does not include these delimiters in the string
1559          * returned.
1560          *
1561          * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1562          * the number of characters in the returned string). When EOF is hit, 0 is returned.
1563          *
1564          * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1565          * delimiters. If the limit is hit we fail and return -ENOBUFS.
1566          *
1567          * If a line shall be skipped ret may be initialized as NULL. */
1568
1569         if (ret) {
1570                 if (!GREEDY_REALLOC(buffer, allocated, 1))
1571                         return -ENOMEM;
1572         }
1573
1574         {
1575                 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
1576                 flockfile(f);
1577
1578                 for (;;) {
1579                         int c;
1580
1581                         if (n >= limit)
1582                                 return -ENOBUFS;
1583
1584                         errno = 0;
1585                         c = fgetc_unlocked(f);
1586                         if (c == EOF) {
1587                                 /* if we read an error, and have no data to return, then propagate the error */
1588                                 if (ferror_unlocked(f) && n == 0)
1589                                         return errno > 0 ? -errno : -EIO;
1590
1591                                 break;
1592                         }
1593
1594                         count++;
1595
1596                         if (IN_SET(c, '\n', 0)) /* Reached a delimiter */
1597                                 break;
1598
1599                         if (ret) {
1600                                 if (!GREEDY_REALLOC(buffer, allocated, n + 2))
1601                                         return -ENOMEM;
1602
1603                                 buffer[n] = (char) c;
1604                         }
1605
1606                         n++;
1607                 }
1608         }
1609
1610         if (ret) {
1611                 buffer[n] = 0;
1612
1613                 *ret = TAKE_PTR(buffer);
1614         }
1615
1616         return (int) count;
1617 }