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