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