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