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