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